UISegmentedControl под UINavigationbar в iOS 7


97

Как сделать , UISegmentedControlкак часть UINavigationBarпод ним? Это связано с UINavigationBarили это полностью отдельное представление, только что добавленное как подпредставление к UINavigationControllerконтроллеру представления. Похоже, это часть UINavigationBarпанели, поскольку под полосой есть тень.

введите описание изображения здесь


Для вас важно сохранить эффект размытия по умолчанию на панели навигации?
— vokilam

Ответы:


150

Это простой эффект.

Сначала разместите сегмент на панели инструментов. Разместите эту панель инструментов прямо под панелью навигации. Установи делегат на панели инструментов на ваш контроллер представления, и вернуться UIBarPositionTopAttachedв positionForBar:. Если выполнить интерактивный всплывающий жест, вы можете увидеть в приложении магазина, что полоса сегментов не перемещается так же, как панель навигации. Это потому, что это не одна и та же планка.

введите описание изображения здесь

Теперь удалим линию роста волос. «Линия роста волос» - это UIImageViewчасть панели навигации. Вы можете найти его и сделать скрытым. Это то, что Apple делает, например, в своем родном приложении-календаре, а также в приложении для магазина. Не забудьте показать его, когда текущий вид исчезнет. Если вы немного поиграете с приложениями Apple, вы увидите, что линия волос скрыта viewWillAppear:и отображается viewDidDisappear:.

Чтобы добиться стиля строки поиска, просто установите для нее searchBarStyleзначение UISearchBarStyleMinimal.


6
Хороший ответ! Не забудьте обновить contentInset tableView, чтобы toolBar не закрыл содержимое :-)
— LombaX

1
«Разместите эту панель инструментов прямо под панелью навигации». Какой должен быть superView?
— koen

1
@Koen Ваш вариант использования более сложный. Создайте контроллер представления контейнера и добавьте туда свой сегмент. Затем добавьте другие контроллеры в качестве дочерних контроллеров в сегментный контроллер.
— Лео Натан,

2
Все еще не понимаете, как лучше всего добавить панель инструментов, следует ли жестко закодировать фрейм initWithRect: CGRectMake(0, self.toplayoutGuide.length, 320, 44)или, может быть, использовать автоматическое размещение для его размещения? Какой будет новая вершина childViews self.toplayoutGuide.length + 44?
— Коэн

1
@Vrutin Не используйте кнопку панели. Вместо этого добавьте как подвид панели инструментов. Затем вы можете установить размер, равный размеру панели инструментов.
— Лео Натан,

14

Теперь удалим линию роста волос. «Линия роста волос» - это 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 .


13

Вот протоколно-ориентированный подход Swift к этой конкретной проблеме, основанный на принятом ответе:

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
  }

}

«Линия роста волос» - это shadowImageсвойство панели навигации.
— LShi

1
Привет, не могли бы вы объяснить, как вы разместили панель инструментов в Interface Builder? Автоматический макет? Не могли бы вы также прокомментировать расширение выше и посмотреть, что произойдет? Не думаю, что это эффективно.
— LShi

8

Вы можете найти панель навигации с UISegmentedControl в образце кода Apple: https://developer.apple.com/library/ios/samplecode/NavBar/Introduction/Intro.html

Или вы можете создать его программно, вот код из моего ответа в другом потоке Добавить сегментированный элемент управления на панель навигации и сохранить заголовок с помощью кнопок


6

Я хотел сделать то же самое .. И получил вот что:


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 - Добавьте свой UISegmentedControl в navigationBar

введите описание изображения здесь


4 - Беги и развлекайся -> не забудьте поставить одинаковый цвет на обоих

введите описание изображения здесь


источник поиска:

Взлом UINavigationBar

ТАК вопрос


Обратите внимание, что UINavigationButtonэто частный API, и ваше приложение будет отклонено за его использование. Вы должны попытаться замаскировать использование этого класса.
— Лео Натан

@LeoNatan после поиска, я решил рискнуть отправить свое приложение в магазин, как в моем ответе, и жас! одобрено
— iTSangar 05

1
Помните, что даже если вы будете одобрены один раз, вы рискуете получить отказ в будущем, или Apple может отклонить при отправке в будущем. По крайней мере, сделайте крошечный объем работы, чтобы скрыть использование частного API.
— Лео Натан

1
У вас отличное решение, я могу добавить что угодно на панель навигации, но, к сожалению, я не могу щелкнуть ни один объект, добавленный в представление: / (Приложение, над которым я работаю, предназначено для устройства JB и не переходит в магазин приложений )
— iDev

1
Выглядит неплохо, за исключением кнопки «Назад», которая добавлена ​​внизу.
— gklka 02

2

У Apple есть пример приложения специально для этого. В нем описывается установка прозрачного теневого изображения и цветного фонового изображения для панели навигации, а также способы настройки представления под панелью навигации. В нем также есть примеры других настроек панели навигации.

См. Https://developer.apple.com/library/ios/samplecode/NavBar/Introduction/Intro.html.


2

Я пробовала удалить линию роста волос методом @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
}

Надеюсь, это кому-то поможет!


2

UISegmentedControl под UINavigationbar в Swift 3/4

подробности

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>

Полученные результаты

введите описание изображения здесь введите описание изображения здесь введите описание изображения здесь


Замечательно и своевременно написать. Спасибо Василий
— daspianist

В любом случае, вы могли бы загрузить для этого проект XCode? Думаю, я неправильно настраиваю панель навигации. Например, я заметил, что это заголовок на белом фоне, а не на стандартном сером. Спасибо
— daspianist

Этот код - полная копия моего проекта. Скопируйте все файлы. Или расскажи мне о своей ошибке.
— Василий Боднарчук

Фантастика! Спасибо!
— daspianist

Используете ли вы вторую панель навигации (содержащую сегментированный элемент управления) в дополнение к той, которая предоставляется UINavigationController?
— LShi

0

Есть много способов сделать то, о чем вы просили. Самый простой из них - это, конечно, просто создать его в построителе интерфейса, но я предполагаю, что это не то, что вы имели в виду. Я создал пример изображения, которое вы разместили выше. Это не совсем то же самое, но вы можете поиграть с многочисленными свойствами, чтобы получить представление о том, что вы ищете.

В 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

-2

DisplaySearchBarInNavigationBar - это способ отображения панели поиска, а также ее области видимости на панели навигации.

вам нужно просто скрыть панель поиска всякий раз, когда вы показываете настраиваемый заголовок


Я не понимаю. Не могли бы вы предоставить исходный код?
— yoeriboven

Говорят, что «панель поиска, отображаемая в панели навигации, не может иметь панель видимости».
— vokilam
Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.