如何动态地将UINavigationBar中UISegmentedControl的宽度设置为最大宽度?

时间:2014-09-03 17:35:35

标签: ios objective-c uinavigationbar uisegmentedcontrol

这是我目前正在使用的代码。不幸的是,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

3 个答案:

答案 0 :(得分:2)

虽然这有些晦涩并且不知道你正在寻找的整个行为(比如旋转时会发生什么?),但我并没有立即看到一种方法来设置宽度。试试这个和/或改变它以满足您的需求:

// 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];

答案 1 :(得分:1)

使用UISegmentControl的API为每个细分设置显式宽度

func setWidth(_ width: CGFloat, forSegmentAtIndex segment: Int)

答案 2 :(得分:0)

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

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