2014-09-03 62 views
3

这是我目前使用的代码。不幸的是,UISegmentControl不是该条的最大宽度。有没有一种快速简便的方法可以将代码的最大宽度设置为不需要精确的帧宽来设置?如何将UINavigationBar中的UISegmentControl的宽度动态设置为最大宽度?

UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                        target:self 
                        action:@selector(addItem:)] autorelease]; 
    self.navigationItem.rightBarButtonItem = addButton; 


    UISegmentedControl *segBar = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"First", @"Second", @"Third", nil]] autorelease]; 
    [segBar setSegmentedControlStyle:UISegmentedControlStyleBar]; 
    [segBar sizeToFit]; 
    self.navigationItem.titleView = segBar; 

下面是它目前的样子:

enter image description here

这是我希望它看起来像:

enter image description here

回答

2

虽然这是轻微的hackish,而不是知道你正在寻找的整个行为(比如当它旋转时会发生什么?),我没有立即看到一种方法很好的宽度。尝试了这一点和/或改变,以适合您的需要:

// this takes the width of the view, gets 80% of that width (to allow for space to the left of the nav button) and 
// divides it by 3 for each individual segment 
CGFloat approxWidth = (CGRectGetWidth(self.view.frame) * .80)/3; 
[[UISegmentedControl appearance] setWidth:approxWidth forSegmentAtIndex:0]; 
[[UISegmentedControl appearance] setWidth:approxWidth forSegmentAtIndex:1]; 
[[UISegmentedControl appearance] setWidth:approxWidth forSegmentAtIndex:2]; 

// create the segmented control and set it as the title view 
UISegmentedControl *segBar = [[UISegmentedControl alloc] initWithItems:@[@"First", @"Second", @"Third"]]; 
self.navigationItem.titleView = segBar; 

产生用于iPhone和iPad以下结果:

enter image description here enter image description here

编辑:值得注意的一些事情好吧,它看起来不像你的代码是使用ARC,我会高度建议,你使用setSegmentedControlStyle,这是iOS7中弃用,并有一个更简单/更清洁的方式来创建一个NSArray:

NSArray *array = @[object1, object2]; 

// the above is much cleaner than 
NSArray *array = [NSArray arrayWithObjects:object1, object2, nil]; 
+0

谢谢,这符合我的需求。我没有使用ARC,因为我正在修改其他人的旧项目。我稍后会解决这个问题。 – 2014-09-03 18:14:07

+0

非常好,很高兴帮助!祝你好运! – Mike 2014-09-03 18:14:37

0

我会继承UISegmentedControl如果你还没有,然后覆盖sizeThatFits这样的:

override func sizeThatFits(size: CGSize) -> CGSize { 
    return CGSize(width: size.width, height: super.sizeThatFits(size).height) 
} 
1

使用UISegmentControl的API来设定明确的宽度为每个段

func setWidth(_ width: CGFloat, forSegmentAtIndex segment: Int) 
相关问题