Iphone 按钮宽度和高零点?
我有这个Iphone 按钮宽度和高零点?,iphone,ios,ipad,Iphone,Ios,Ipad,我有这个 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchDown]; [button setTitle:NSLocalizedString(@"Action", @"")
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;
此时宽度为零
零
有什么线索吗?由于您没有设置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
设置标题标签后,在按钮上调用sizeToFit。这将根据您刚刚设置的文本适当调整其大小
无论如何,在绘制之前,按钮会调用它,但是因为您似乎需要它,所以您可以自己做 您正在创建一个按钮,但没有设置其框架,或者使用interface builder创建按钮,并在加载视图后访问其框架,或者为其提供一个框架,如:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame: CGRectMake (100, 200, 150, 44)];
[button addTarget:self ....