developer tip

iOS 7에서 UINavigationbar 아래의 UISegmentedControl

optionbox 2020. 8. 25. 07:55
반응형

iOS 7에서 UINavigationbar 아래의 UISegmentedControl


아래 UISegmentedControl의 일부로 어떻게 만들 UINavigationBar수 있습니까? 에 연결되어 있습니까 아니면 의 뷰 컨트롤러에 UINavigationBar하위 뷰로 추가 된 완전한 별도의 뷰 입니까? 막대 아래에 그림자가 있기 때문에의 UINavigationController일부인 것 UINavigationBar같습니다.

여기에 이미지 설명 입력


달성 할 수있는 간단한 효과입니다.

먼저 도구 모음에 세그먼트를 배치합니다. 이 도구 모음을 탐색 모음 바로 아래에 배치합니다. 툴바의 델리게이트를 뷰 컨트롤러로 설정 UIBarPositionTopAttached하고 positionForBar:. 스토어 앱에서 대화 형 팝 제스처를 수행하면 세그먼트 바가 탐색 바와 동일하게 움직이지 않음을 알 수 있습니다. 그것은 그들이 같은 바가 아니기 때문입니다.

여기에 이미지 설명 입력

이제 헤어 라인을 제거합니다. "헤어 라인"은 UIImageView탐색 모음의 하위보기입니다. 그것을 찾아서 숨김으로 설정할 수 있습니다. 예를 들어 Apple이 기본 캘린더 앱과 스토어 앱에서 수행하는 작업입니다. 현재보기가 사라질 때 표시해야합니다. Apple 앱으로 조금 플레이하면 헤어 라인이 숨김으로 viewWillAppear:설정되고에 표시되도록 설정되어 있음을 알 수 viewDidDisappear:있습니다.

검색 창의 스타일을 얻으려면 막대를로 설정하면 searchBarStyle됩니다 UISearchBarStyleMinimal.


이제 헤어 라인을 제거합니다. "헤어 라인"은 탐색 모음의 하위보기 인 UIImageView입니다. 그것을 찾아서 숨김으로 설정할 수 있습니다. 예를 들어 Apple이 기본 캘린더 앱과 스토어 앱에서 수행하는 작업입니다. 현재보기가 사라질 때 표시해야합니다. Apple 앱으로 조금 플레이하면 헤어 라인이 viewWillAppear :에서 숨김으로 설정되고 viewDidDisappear :에 표시되도록 설정되어 있음을 알 수 있습니다.

또 다른 방법은 헤어 라인을 찾아 추가 된 도구 모음 아래로 이동하는 것입니다. 여기 내가 생각 해낸 것이 있습니다.

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIToolbar *segmentbar;
@property (weak, nonatomic) UIImageView *navHairline;
@end

@implementation ViewController

#pragma mark - View Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // find the hairline below the navigationBar
    for (UIView *aView in self.navigationController.navigationBar.subviews) {
        for (UIView *bView in aView.subviews) {
            if ([bView isKindOfClass:[UIImageView class]] &&
                bView.bounds.size.width == self.navigationController.navigationBar.frame.size.width &&
                bView.bounds.size.height < 2) {
                self.navHairline = (UIImageView *)bView;
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self _moveHairline:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self _moveHairline:NO];
}

- (void)_moveHairline:(BOOL)appearing
{
    // move the hairline below the segmentbar
    CGRect hairlineFrame = self.navHairline.frame;
    if (appearing) {
        hairlineFrame.origin.y += self.segmentbar.bounds.size.height;
    } else {
        hairlineFrame.origin.y -= self.segmentbar.bounds.size.height;
    }
    self.navHairline.frame = hairlineFrame;
}

@end

또한 Apple NavBar 코드 샘플 (UINavigationBar 사용자 지정) 이이 문제를 해결하는 데 매우 유용 하다는 것을 알았습니다 .

또한 UIToolbar의 상단 테두리처리 해야합니다. 표시 될 수 있으며 NavBar의 헤어 라인과 혼동 될 수 있습니다. 또한 UIToolbar가 NavBar와 똑같이 보이기를 원했습니다 . 그러면 도구 모음barTintColor조정하고 싶을 것입니다 .


이 특정 문제에 대한 프로토콜 지향 스위프트 접근 방식은 수용된 답변을 기반으로합니다.

HideableHairlineViewController.swift

protocol HideableHairlineViewController {

  func hideHairline()
  func showHairline()

}

extension HideableHairlineViewController where Self: UIViewController {

  func hideHairline() {
    findHairline()?.hidden = true
  }

  func showHairline() {
    findHairline()?.hidden = false
  }

  private func findHairline() -> UIImageView? {
    return navigationController?.navigationBar.subviews
      .flatMap { $0.subviews }
      .flatMap { $0 as? UIImageView }
      .filter { $0.bounds.size.width == self.navigationController?.navigationBar.bounds.size.width }
      .filter { $0.bounds.size.height <= 2 }
      .first
  }

}

SampleViewController.swift

import UIKit

class SampleViewController: UIViewController, HideableHairlineViewController {

  @IBOutlet private weak var toolbar: UIToolbar!
  @IBOutlet private weak var segmentedControl: UISegmentedControl!

  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    hideHairline()
  }

  override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    showHairline()
  }


}

// MARK: UIToolbarDelegate
extension SampleViewController: UIToolbarDelegate {

  func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
    return .TopAttached
  }

}

Apple 샘플 코드 : https://developer.apple.com/library/ios/samplecode/NavBar/Introduction/Intro.html 에서 UISegmentedControl이있는 탐색 모음을 찾을 수 있습니다.

또는 프로그래밍 방식으로 만들 수 있습니다. 다른 스레드의 내 대답에있는 코드는 탐색 모음에 세그먼트 화 된 컨트롤을 추가하고 버튼으로 제목을 유지합니다.


나는 똑같은 일을하고 싶었다. 그리고 이것을 얻었다 :


1-UINavigationBar 하위 클래스

//-------------------------
// UINavigationBarCustom.h
//-------------------------
#import <UIKit/UIKit.h>

@interface UINavigationBarCustom : UINavigationBar

@end


//-------------------------
// UINavigationBarCustom.m
//-------------------------
#import "UINavigationBarCustom.h"

const CGFloat MyNavigationBarHeightIncrease = 38.f;

@implementation UINavigationBarCustom


- (id)initWithCoder:(NSCoder *)aDecoder {

    self = [super initWithCoder:aDecoder];

    if (self) {
        [self initialize];
    }

    return self;
}

- (id)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];

    if (self) {
        [self initialize];
    }

    return self;
}

- (void)initialize {
    // Set tittle position for top
    [self setTitleVerticalPositionAdjustment:-(MyNavigationBarHeightIncrease) forBarMetrics:UIBarMetricsDefault];
}

- (CGSize)sizeThatFits:(CGSize)size {
    // Increase NavBar size
    CGSize amendedSize = [super sizeThatFits:size];
    amendedSize.height += MyNavigationBarHeightIncrease;

    return amendedSize;
}

- (void)layoutSubviews {
// Set buttons position for top
    [super layoutSubviews];

    NSArray *classNamesToReposition = @[@"UINavigationButton"];

    for (UIView *view in [self subviews]) {

        if ([classNamesToReposition containsObject:NSStringFromClass([view class])]) {

            CGRect frame = [view frame];
            frame.origin.y -= MyNavigationBarHeightIncrease;

            [view setFrame:frame];
        }
    }
}

- (void)didAddSubview:(UIView *)subview
{
    // Set segmented position
    [super didAddSubview:subview];

    if ([subview isKindOfClass:[UISegmentedControl class]])
    {
        CGRect frame = subview.frame;
        frame.origin.y += MyNavigationBarHeightIncrease;
        subview.frame = frame;
    }
}

@end

2-하위 클래스로 NavigationController 설정

하위 클래스로 NavigationController 설정


3-navigationBar에 UISegmentedControl 추가

여기에 이미지 설명 입력


4-달리기와 재미 -> 둘 다에 같은 색을 입히는 것을 잊지 마십시오

여기에 이미지 설명 입력


소스 검색 :

UINavigationBar 해킹

그래서 질문


Apple에는이를위한 샘플 앱이 있습니다. 내비게이션 바에 투명한 그림자 이미지와 컬러 배경 이미지를 설정하고 내비게이션 바 아래에보기를 구성하는 방법에 대해 설명합니다. 또한 다른 탐색 모음 사용자 정의의 예가 있습니다.

참조 https://developer.apple.com/library/ios/samplecode/NavBar/Introduction/Intro.html를


@Simon의 방법을 사용하여 헤어 라인을 제거하려고 시도했지만 작동하지 않았습니다. 나는 슈퍼 멍청이이기 때문에 뭔가 잘못하고있을 것입니다. 그러나 줄을 제거하는 대신 hidden속성을 사용하여 간단히 숨길 수 있습니다 . 코드는 다음과 같습니다.

var hairLine: UIView = UIView()
override func viewDidLoad() {
    super.viewDidLoad()
    doneButton.enabled = false

    for parent in self.navigationController!.navigationBar.subviews {
        for childView in parent.subviews {
            if childView is UIImageView && childView.bounds.size.width == self.navigationController!.navigationBar.frame.size.width {
                hairLine = childView
            }
        }
    }
}

override func viewWillAppear(animated: Bool) {
    hairLine.hidden = true
}

override func viewWillDisappear(animated: Bool) {
    hairLine.hidden = false
}

이것이 누군가를 돕기를 바랍니다!


신속한 3/4의 UINavigationbar 아래 UISegmentedControl

세부

Xcode 9.2, 스위프트 4

전체 샘플

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var navigationBarWithSegmentedControl: UINavigationBar!

    fileprivate let barBackgroundColor = UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1.0)

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBarWithSegmentedControl.barTintColor = barBackgroundColor
        tableView.dataSource = self
        tableView.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.barTintColor = barBackgroundColor
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        navigationController?.navigationBar.shadowImage =  nil
    }
}

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        cell.label.text = "\(indexPath)"
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.isSelected = false
        }
    }
}

TableViewCell.swift

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var label: UILabel!

}

Main.storyboard

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13771" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="5TT-dT-dEr">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13772"/>
        <capability name="Constraints to layout margins" minToolsVersion="6.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Text-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_21887252" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="603"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="HLl-W2-Moq">
                                <rect key="frame" x="0.0" y="44" width="375" height="559"/>
                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                                <prototypes>
                                    <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="TableViewCell" id="FKA-c2-G0Q" customClass="TableViewCell" customModule="stackoverflow_21887252" customModuleProvider="target">
                                        <rect key="frame" x="0.0" y="28" width="375" height="44"/>
                                        <autoresizingMask key="autoresizingMask"/>
                                        <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="FKA-c2-G0Q" id="Xga-fr-00H">
                                            <rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
                                            <autoresizingMask key="autoresizingMask"/>
                                            <subviews>
                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="QW3-Hg-hU9">
                                                    <rect key="frame" x="15" y="11" width="345" height="21"/>
                                                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                    <nil key="textColor"/>
                                                    <nil key="highlightedColor"/>
                                                </label>
                                            </subviews>
                                            <constraints>
                                                <constraint firstAttribute="trailingMargin" secondItem="QW3-Hg-hU9" secondAttribute="trailing" id="Grx-nu-2Tu"/>
                                                <constraint firstItem="QW3-Hg-hU9" firstAttribute="centerY" secondItem="Xga-fr-00H" secondAttribute="centerY" id="MIn-R2-wYE"/>
                                                <constraint firstItem="QW3-Hg-hU9" firstAttribute="leading" secondItem="Xga-fr-00H" secondAttribute="leadingMargin" id="h6T-gt-4xk"/>
                                            </constraints>
                                        </tableViewCellContentView>
                                        <color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.050000000000000003" colorSpace="custom" customColorSpace="sRGB"/>
                                        <connections>
                                            <outlet property="label" destination="QW3-Hg-hU9" id="QjK-i2-Ckd"/>
                                            <segue destination="hcx-2g-4ts" kind="show" id="IGa-oI-gtf"/>
                                        </connections>
                                    </tableViewCell>
                                </prototypes>
                            </tableView>
                            <navigationBar contentMode="scaleToFill" translucent="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8jj-w6-ZtU">
                                <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                                <items>
                                    <navigationItem id="q8e-Yy-ceD">
                                        <nil key="title"/>
                                        <segmentedControl key="titleView" opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="bar" selectedSegmentIndex="0" id="cHD-bv-2w7">
                                            <rect key="frame" x="96.5" y="7" width="182" height="30"/>
                                            <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                            <segments>
                                                <segment title="First"/>
                                                <segment title="Second"/>
                                                <segment title="Third"/>
                                            </segments>
                                        </segmentedControl>
                                    </navigationItem>
                                </items>
                            </navigationBar>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="8jj-w6-ZtU" firstAttribute="trailing" secondItem="HLl-W2-Moq" secondAttribute="trailing" id="1vT-ta-AuP"/>
                            <constraint firstItem="8jj-w6-ZtU" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="BJE-BC-XcB"/>
                            <constraint firstItem="8jj-w6-ZtU" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="Boi-dN-awt"/>
                            <constraint firstItem="HLl-W2-Moq" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="W1n-m1-EOH"/>
                            <constraint firstAttribute="trailing" secondItem="8jj-w6-ZtU" secondAttribute="trailing" id="ihc-9p-71l"/>
                            <constraint firstItem="HLl-W2-Moq" firstAttribute="top" secondItem="8jj-w6-ZtU" secondAttribute="bottom" id="pFk-pU-y7j"/>
                            <constraint firstItem="8jj-w6-ZtU" firstAttribute="leading" secondItem="HLl-W2-Moq" secondAttribute="leading" id="yjf-7o-t2m"/>
                        </constraints>
                    </view>
                    <navigationItem key="navigationItem" title="Text" id="yrt-M7-PAX">
                        <barButtonItem key="leftBarButtonItem" systemItem="search" id="wrz-DS-FdJ"/>
                        <barButtonItem key="rightBarButtonItem" systemItem="add" id="LnB-Ci-YnO"/>
                    </navigationItem>
                    <connections>
                        <outlet property="navigationBarWithSegmentedControl" destination="8jj-w6-ZtU" id="Ggl-xb-fmj"/>
                        <outlet property="tableView" destination="HLl-W2-Moq" id="hEO-2U-I9k"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="894" y="791"/>
        </scene>
        <!--View Controller-->
        <scene sceneID="Bi7-4l-uRN">
            <objects>
                <viewController id="hcx-2g-4ts" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="NSV-kw-fuz"/>
                        <viewControllerLayoutGuide type="bottom" id="aze-le-h11"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="1nd-qq-kDT">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="603"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="k7W-CB-tpA">
                                <rect key="frame" x="0.0" y="0.0" width="375" height="603"/>
                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            </view>
                        </subviews>
                        <color key="backgroundColor" white="0.66666666666666663" alpha="0.5" colorSpace="calibratedWhite"/>
                        <constraints>
                            <constraint firstAttribute="trailing" secondItem="k7W-CB-tpA" secondAttribute="trailing" id="1t2-Bi-dR7"/>
                            <constraint firstItem="k7W-CB-tpA" firstAttribute="bottom" secondItem="aze-le-h11" secondAttribute="top" id="Fnm-UL-geX"/>
                            <constraint firstItem="k7W-CB-tpA" firstAttribute="leading" secondItem="1nd-qq-kDT" secondAttribute="leading" id="bKV-7A-hz0"/>
                            <constraint firstItem="k7W-CB-tpA" firstAttribute="top" secondItem="NSV-kw-fuz" secondAttribute="bottom" id="cFH-7i-vAm"/>
                        </constraints>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="jPK-Z9-yvJ" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="1566" y="791"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="1Pc-qt-rnW">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="5TT-dT-dEr" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" translucent="NO" id="lPt-hx-iar">
                        <rect key="frame" x="0.0" y="20" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="6b8-br-zSy"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="u7U-GH-NHe" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="140" y="791.15442278860576"/>
        </scene>
    </scenes>
</document>

결과

여기에 이미지 설명 입력 여기에 이미지 설명 입력 여기에 이미지 설명 입력


요청한 작업을 수행하는 방법에는 여러 가지가 있습니다. 물론 인터페이스 빌더에서 생성하는 것이 가장 쉬운 방법이지만, 이것이 당신이 염두에 두었던 것이 아니라고 생각합니다. 위에 게시 한 이미지의 예를 만들었습니다. 정확히 똑같지는 않지만 수많은 속성을 가지고 플레이하여 원하는 모양과 느낌을 얻을 수 있습니다.

ViewController.h에서

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@end

ViewController.m에서

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) UISegmentedControl *mySegmentControl;
@property (strong, nonatomic) UISearchBar *mySearchBar;
@property (strong, nonatomic) UITableView *myTableView;
@property (strong, nonatomic) NSMutableArray *tableDataArray;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// create a custom UIView
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, 320, 84)];
myView.tintColor = [UIColor lightGrayColor]; // change tiny color or delete this line to default

// create a UISegmentControl
self.mySegmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"All", @"Not on this iPhone", nil]];
self.mySegmentControl.selectedSegmentIndex = 0;
[self.mySegmentControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
self.mySegmentControl.frame = CGRectMake(20, 10, 280, 30);
[myView addSubview:self.mySegmentControl]; // add segment control to custom view

// create UISearchBar
self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 40, 320, 44)];
[self.mySearchBar setDelegate:self];
self.mySearchBar.searchBarStyle = UISearchBarStyleMinimal;
[myView addSubview:self.mySearchBar]; // add search bar to custom view

[self.view addSubview:myView]; // add custom view to main view

// create table data array
self.tableDataArray = [[NSMutableArray alloc] initWithObjects:
                       @"Line 1",
                       @"Line 2",
                       @"Line 3",
                       @"Line 4",
                       @"Line 5",
                       @"Line 6",
                       @"Line 7",
                       @"Line 8",
                       @"Line 9",
                       @"Line 10",
                       @"Line 11",
                       @"Line 12", nil];
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 160, 320, 320)];
[self.myTableView setDataSource:self];
[self.myTableView setDelegate:self];
[self.view addSubview:self.myTableView]; // add table to main view
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
NSLog(@"search text = %@",searchBar.text);
// code for searching...
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.tableDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
    {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

cell.textLabel.text = [self.tableDataArray objectAtIndex:indexPath.row];

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Selected table item: %@",[self.tableDataArray objectAtIndex:indexPath.row]);

// do something once user has selected a table cell...
}

-(void)segmentAction:(id)sender {
NSLog(@"Segment control changed to: %@",[self.mySegmentControl titleForSegmentAtIndex:[self.mySegmentControl selectedSegmentIndex]]);

// do something based on segment control selection...
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

displaysSearchBarInNavigationBar 는 탐색 표시 줄에 검색 표시 줄과 스코프 표시 줄을 표시하는 방법입니다.

맞춤 제목을 표시 할 때마다 검색 창을 숨기면됩니다.

참고 URL : https://stackoverflow.com/questions/21887252/uisegmentedcontrol-below-uinavigationbar-in-ios-7

반응형