UI按钮宽度和高零?

Spa*_*Dog 0 iphone ipad ios

我有这个

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;
Run Code Online (Sandbox Code Playgroud)

此时宽度为零......

零?

任何线索为什么?

ask*_*sif 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
Run Code Online (Sandbox Code Playgroud)