【问题标题】:UISegmentedControl below UINavigationbar in iOS 7iOS 7 中 UINavigationbar 下方的 UISegmentedControl
【发布时间】:2014-03-20 04:23:13
【问题描述】:

如何使UISegmentedControl 成为其下方UINavigationBar 的一部分?它是连接到UINavigationBar 还是作为子视图添加到UINavigationController 的视图控制器的一个完整的单独视图。看起来它是UINavigationBar 的一部分,因为条形下方有一个阴影。

【问题讨论】:

  • 在导航栏上保持默认模糊效果对您来说重要吗?

标签: ios uinavigationbar uisegmentedcontrol


【解决方案1】:

有很多方法可以按照您的要求进行。最简单的方法当然是在界面构建器中创建它,但我认为这不是您的想法。我创建了您在上面发布的图像的示例。它并不完全相同,但您可以使用众多属性来获得您正在寻找的外观和感觉。

在 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】:

    UINavigationbar 下方的 UISegmentedControl 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>
    

    结果

    【讨论】:

    • 伟大而及时的写作。谢谢瓦西里
    • 有什么办法可以为此上传 XCode 项目?我想我没有正确配置我的导航栏。例如,我注意到它是白色背景标题而不是标准灰色。谢谢
    • 此代码 - 我的项目的完整副本。复制所有文件。或者告诉我你的错误。
    • 太棒了!谢谢!
    • 除了UINavigationController提供的导航栏之外,您是否还在使用第二导航栏(包含分段控件的导航栏)?
    【解决方案3】:

    这是针对这个特定问题的面向协议的 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属性。
    • 您好,您能解释一下您是如何在 Interface Builder 中放置工具栏的吗?自动布局?您能否也注释掉上面的扩展名,看看会发生什么?我认为它没有效果。
    【解决方案4】:

    我尝试使用@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
    }
    

    希望这对某人有所帮助!

    【讨论】:

      【解决方案5】:

      Apple 专门为此提供了示例应用程序。它描述了为导航栏设置透明阴影图像和彩色背景图像以及如何配置导航栏下方的视图。它还包含其他导航栏自定义的示例。

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

      【讨论】:

        【解决方案6】:

        现在去除发际线。 “细线”是一个 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 Code Sample (Customizing UINavigationBar) 对解决此问题很有帮助。

        也一定要handle the top border of the UIToolbar,它可能会出现,你可能会将它与导航栏的细线混淆。我还希望 UIToolbar 看起来与 NavBar 完全一样,那么您可能想要adjust the Toolbars barTintColor

        【讨论】:

          【解决方案7】:

          您可以在 Apple 示例代码中找到带有 UISegmentedControl 的导航栏:https://developer.apple.com/library/ios/samplecode/NavBar/Introduction/Intro.html

          或者您可以以编程方式创建它,这是我在另一个线程中的答案中的代码 Add segmented control to navigation bar and keep title with buttons

          【讨论】:

            【解决方案8】:

            我想做同样的事情..得到了这个:


            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


            3 - 在导航栏中添加您的 UISegmentedControl


            4 - 跑步和娱乐 ->不要忘记在两个颜色上涂上相同的颜色


            搜索来源:

            Hacking UINavigationBar

            S.O question

            【讨论】:

            • 请注意UINavigationButton是私有API,你的应用会被拒绝使用它。您应该尝试屏蔽该类的使用。
            • @LeoNatan 搜索后我决定冒险将我的应用程序发送到商店,因为它在我的答案和 zhas 中!批准
            • 请记住,即使您被批准一次,您也有可能在未来的某个日期被拒绝,或者 Apple 可能会在未来提交时拒绝。至少做少量的工作来隐藏私有 API 的使用。
            • 您的解决方案很棒,我可以在导航栏中添加任何内容,但不幸的是我无法单击添加到视图中的任何对象:/(我正在开发的应用程序是JB设备而不去Appstore)
            • 看起来不错,除了后退按钮,恰好加到了底部。
            【解决方案9】:

            这是一个简单的效果。

            首先,在工具栏中放置一个段。将此工具栏放在导航栏的正下方。将工具栏的委托设置为您的视图控制器,并在positionForBar: 中返回UIBarPositionTopAttached。您可以在商店应用程序中看到,如果您执行交互式弹出手势,则分段栏与导航栏的移动方式不同。那是因为他们不是同一个酒吧。

            现在去除发际线。 “细线”是一个UIImageView,它是导航栏的子视图。您可以找到它并将其设置为隐藏。例如,这就是 Apple 在其本地日历应用程序以及商店应用程序中所做的事情。记得在当前视图消失时显示它。如果你稍微玩一下苹果应用程序,你会看到发际线在viewWillAppear: 上设置为隐藏,在viewDidDisappear: 上设置为显示。

            要实现搜索栏的样式,只需将搜索栏的searchBarStyle设置为UISearchBarStyleMinimal即可。

            【讨论】:

            • 好答案!不要忘记更新tableView的contentInset以避免toolBar覆盖内容:-)
            • "将此工具栏放在导航栏的正下方。" superView 应该是什么?
            • @Koen 您的用例更复杂。创建一个容器视图控制器,并在那里添加你的段。然后将其他控制器添加为段控制器下的子控制器。
            • 仍然对添加工具栏的最佳方法感到困惑,我应该在initWithRect: CGRectMake(0, self.toplayoutGuide.length, 320, 44) 中对框架进行硬编码,还是使用自动布局来定位它? childViews 的新顶部是什么,是 self.toplayoutGuide.length + 44 吗?
            • @Vrutin 不要使用条形按钮项目。相反,添加为工具栏的子视图。然后,您可以将大小设置为工具栏的大小。
            【解决方案10】:

            displaysSearchBarInNavigationBar 是在导航栏中显示搜索栏及其范围栏的方式。

            您只需在显示自定义标题时隐藏搜索栏

            【讨论】:

            • 我不明白。能否提供一些源代码?
            • 据说“在导航栏中显示的搜索栏不能有范围栏。”
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-07-19
            • 2013-09-20
            • 2014-03-03
            相关资源
            最近更新 更多