【发布时间】:2023-03-29 17:36:01
【问题描述】:
我真的需要你的帮助(关于 SO 的第一篇文章——要温柔):
我有两个动态 UIButton,我希望它们位于 UIView 的中心,而 UIView 又应位于 UINavigationbar 和 UIToolbar 的中心。我无法 - 尽管有很多谷歌搜索 - 似乎找到了一个正确的方法来做到这一点。
这是我到目前为止所做的:
在viewDidLoad中,我将两个按钮添加为子视图,并将视图设置为UINavigationbar的titleView
self.myClass.viewForTitleAndButton = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 32)];
[self.myClass.viewForTitleAndButton setBackgroundColor:[UIColor blackColor]];
[self.myClass.viewForTitleAndButton addSubview:self.myClass.myButton];
[self.myClass.viewForTitleAndButton addSubview:self.myClass.myOtherButton];
self.navigationItem.titleView = self.myClass.viewForTitleAndButton;
在我按下某些按钮时触发的方法中,我根据点击的内容设置其中一个按钮的标题(和边界):
CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName : [UIFont italicSystemFontOfSize:17.0]}];
CGSize screenSize = [UIScreen mainScreen].bounds.size;
CGFloat newX = (screenSize.width - titleSize.width) / 2;
CGRect buttonFrame = self.myClass.myButton.frame;
//Removing the line below doesn't do any difference at the moment
self.myClass.myButton.bounds = CGRectMake(newX, buttonFrame.origin.y, titleSize.width+8, buttonFrame.size.height);
[self.myClass.myButton setTitle:title forState:UIControlStateNormal];
NSLog(@"Title: %@", title);
//title is a NSString that changes depending on what is clicked. I am 100% sure it changes as I can see it in the log every time the method is triggered.
问题是 myButton 的标题没有改变。当它被放置在不同的位置而不是作为子视图时,它之前使用相同的按钮工作。
Q1:我缺少什么来改变按钮的标题?
Q2:将按钮作为子视图添加到视图中,然后分别放置在导航栏和工具栏中,这是实现我想要的合理方式吗?
这真的让我很烦恼,非常感谢任何正确方向的指针。
【问题讨论】:
-
界限在变吗?还是这也不起作用?
-
附加信息:myButton 有一个插座。我已经尝试过弱参考和强参考。
-
@Merlevede:我在 myButton 中添加了紫色背景颜色,紫色区域的大小保持不变。
-
您的
myButton插座似乎没有链接到 Interface Builder 中的按钮 -
一开始我也怀疑是这样,但我只是检查了三次,它确实是链接的。按钮的标题在它不是 viewForTitleAndButton 的一部分之前已更改。
标签: ios iphone objective-c uinavigationbar title