Swift扩展navigationBar高度并添加segmentControl
问题描述:
我设计了以下UINavigationBar,但是我有点困惑,是否有可能像下面这样添加segmentControl?什么是最好的方式来实现这样的?Swift扩展navigationBar高度并添加segmentControl
答
扩展。 (对不起,不回答彼得的问题。)
在Xcode中,File - New - Swift File - 命名类。
import UIKit
import Foundation
extension UINavigationController
{
func makeBlackNavigationbar(){
print("black navigation")
navigationController?.navigationBarHidden = false
}
}
extension UINavigationBar
{
func makeBlackNavigationBar()
{
barTintColor = UIColor.blackColor()
let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
titleTextAttributes = titleDict as [NSObject : AnyObject]
}
}
它可以在项目的任何地方实施。
self.navigationController?.makeBlackNavigationbar()
self.navigationController?.navigationBar.makeBlackNavigationBar()
答
如下您可以模仿你的要求:
-(void) segmentAction: (UISegmentedControl *) segmentedControl
{
// Update the label with the segment number
NSString *segmentNumber = [NSString stringWithFormat:@"%0d",
segmentedControl.selectedSegmentIndex + 1];
[(UITextView *)self.view setText:segmentNumber];
}
- (void) loadView
{
[super loadView];
// Create a central text view
UITextView *textView = [[UITextView alloc]
initWithFrame:self.view.frame];
textView.font = [UIFont fontWithName:@"Futura" size:96.0f];
textView.textAlignment = UITextAlignmentCenter;
self.view = textView;
// Create the segmented control
NSArray *buttonNames = [NSArray arrayWithObjects:
@"Recent", @"Popular", @"My", nil];
UISegmentedControl* segmentedControl = [[UISegmentedControl alloc]
initWithItems:buttonNames];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
[segmentedControl addTarget:self action:@selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
// Add it to the navigation bar
self.navigationItem.titleView = segmentedControl;
}
或有另一种方法如下:UInavigation吧
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
[NSString stringWithString:NSLocalizedString(@"Recent", @"")],
[NSString stringWithString:NSLocalizedString(@"Popular", @"")],
[NSString stringWithString:NSLocalizedString(@"My", @"")],
nil]];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.tintColor = [UIColor clearColor];
[segmentedControl setSelectedSegmentIndex:0];
[segmentedControl addTarget:self action:@selector(changeSegment:)
forControlEvents:UIControlEventValueChanged];
[segmentedControl setFrame:[self.navigationController.toolbar bounds]];
[self.navigationController.toolbar addSubview:segmentedControl];