【问题标题】:Getting size of a UIButton and right aligning获取 UIButton 的大小和右对齐
【发布时间】:2014-08-11 20:49:21
【问题描述】:

我有一个这样的 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;

那么宽度总是为零。

我希望按钮在我创建的视图中右对齐。

【问题讨论】:

    标签: ios ios7 uibutton


    【解决方案1】:

    正如我所见,您没有设置按钮框架。所以你得到零回报。没有设置框架你不能得到宽度所以首先设置框架使用这样..

    inviteButton.frame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>);;
    

    【讨论】:

      【解决方案2】:

      你必须使用这样的框架为 UIButton 设置高度和宽度。

          inviteButton.frame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
      

      【讨论】:

        【解决方案3】:

        我真的想要这个:

        已弃用。

        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];
        

        【讨论】:

          【解决方案4】:

          你可以用这个设置宽度和高度。

          [inviteButton sizeToFit];

          然后尝试打印这个

          浮动宽度 = 邀请按钮.frame.size.width;

          然后设置按钮的框架以显示在屏幕上的特定位置。

          [inviteButton setFrame:CGRectMake(x,y,inviteButton.frame.size.width,inviteButton.frame.size.height)]

          【讨论】:

            猜你喜欢
            • 2020-08-30
            • 1970-01-01
            • 1970-01-01
            • 2020-09-06
            • 1970-01-01
            • 2022-07-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多