在uinavigationbar和uitoolbar中查看子视图

时间:2014-03-20 03:21:56

标签: ios iphone objective-c uinavigationbar title

我真的需要你的帮助(关于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:将按钮作为子视图添加到视图中,然后分别放置在导航栏和工具栏中,这是实现我想要的声音方式吗?

这真让我烦恼,任何指向正确方向的人都非常感激。

1 个答案:

答案 0 :(得分:0)

我认为你不能添加一个已经是视图控制器插座的按钮。以另一种方式思考,按钮(视图)只能有一个超级视图。

为标题视图动态创建按钮。

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *iv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
    iv.backgroundColor = [UIColor greenColor];
    titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    titleButton.frame = CGRectMake(0, 0, 120, 44);
    [titleButton setTitle:@"test" forState:UIControlStateNormal];
    [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [iv addSubview:titleButton];
    self.navigationItem.titleView = iv;
}

//some event to change the button title
- (void)click:(UIButton *)button
{
    [titleButton setTitle:@"I changed" forState:UIControlStateNormal];
}