UI按钮宽度和高零?

时间:2013-01-23 07:57:32

标签: iphone ios ipad

我有这个

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
              action:@selector(myAction:)
    forControlEvents:UIControlEventTouchDown];

[button setTitle:NSLocalizedString(@"Action", @"")
           forState:UIControlStateNormal];
CGFloat width = button.bounds.size.width;

此时宽度为零...

零?

任何线索为什么?

3 个答案:

答案 0 :(得分:7)

由于您尚未设置UIButton的框架,请将代码修改为

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20,20,50,50);
[button addTarget:self
              action:@selector(myAction:)
    forControlEvents:UIControlEventTouchDown];

[button setTitle:NSLocalizedString(@"Action", @"")
           forState:UIControlStateNormal];
CGFloat width = button.bounds.size.width; // Now the width of button would be 50

答案 1 :(得分:2)

您正在创建一个按钮,但您没有设置其框架,要么使用界面构建器创建它,并在视图加载后访问它的框架,或者给它一个框架,如:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame: CGRectMake (100, 200, 150, 44)];
[button addTarget:self ....

答案 2 :(得分:1)

设置标题标签后,在按钮上调用sizeToFit。这将根据您刚设置的文本进行适当调整。

在绘制之前,它会在按钮上被调用,但由于您似乎需要它,所以您可以自己完成。