我有这样的UIButton:
UIButton *inviteButton = [UIButton buttonWithType:UIButtonTypeSystem];
[inviteButton setTitle:@"Invite" forState:UIControlStateNormal];
[inviteButton.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:(14.0)]];
[inviteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
如何获得它的高度和宽度以便我可以设置它的框架?
如果我这样做:
float width = inviteButton.frame.size.width;
然后宽度始终为零。
我希望按钮在我创建的视图中右对齐。
答案 0 :(得分:3)
你必须使用这样的框架为UIButton设置高度和宽度。
inviteButton.frame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
答案 1 :(得分:1)
您可以使用此设置宽度和高度。
[inviteButton sizeToFit];
之后尝试打印此
float width = inviteButton.frame.size.width;
然后设置按钮框以在特定位置显示在屏幕上。
[inviteButton setFrame:CGRectMake(x,y,inviteButton.frame.size.width,inviteButton.frame.size.height)]
答案 2 :(得分:0)
正如我所见,你没有设置按钮框架。所以你得到ZERO回归。如果没有设置框架,你就无法获得宽度,所以首先使用这样设置框架。
inviteButton.frame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>);;
答案 3 :(得分:0)
我其实想要这个:
这已被弃用。
CGSize size = [[inviteButton titleForState:UIControlStateNormal] sizeWithFont:inviteButton.titleLabel.font];
这是新的方式:
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:(14.0)]};
CGSize size = [[inviteButton titleForState:UIControlStateNormal] sizeWithAttributes:attributes];