gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:55 34 4
gpt4 key购买 nike

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

最佳答案

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

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

关于ios - 如何动态地将 UINavigationBar 中的 UISegmentControl 的宽度设置为最大宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25650437/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com