【问题标题】:UIButton: calculate height of UIButton based on titleLabel TextUIButton:根据titleLabel Text计算UIButton的高度
【发布时间】:2012-09-21 18:32:29
【问题描述】:

我在自定义 UITableViewCell 中有一个自定义 UIButton。我想根据按钮 titleLabel 的可变文本内容在自定义表格单元格中设置 UIButton 的高度。

我尝试了以下方法来计算高度

[NSString sizeWithFont:constrainedToSize:lineBreakMode:];

但我无法根据 titleLabel 成功更改按钮高度。

此外,由于此按钮是自定义 UITableViewCell 的一部分,因此我还需要根据自定义 UIButton 的高度更改单元格的高度。

在实现UITableView的delegate和datasource方法的ViewController中,我尝试在下面的方法中确定高度

- (CGFloat) tableView: (UITableView *) tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath

但没有成功。

解决这个问题的最佳解决方案或方法是什么?

【问题讨论】:

标签: iphone ios uitableview uibutton uilabel


【解决方案1】:

假设您的按钮宽度为 145.0f:

CGSize constraintSize;

constraintSize.width = 145.0f;

constraintSize.height = MAXFLOAT;

CGSize size = [Label.text sizeWithFont:Label.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

然后就可以设置框架了:

frame = CGRectMake(0, 0, 145, size.height);

【讨论】:

    【解决方案2】:

    看起来你做得对,但请记住:

    heightForRowAtIndexPath 必须返回CGFloat sizeWithFont 为您提供文本高度,您需要添加按钮和单元格的填充

    使用constrainedToSize:CGSizeMake(###,MAXFLOAT) 其中### 是您的文本宽度

    lineBreakMode:UILineBreakModeWordWrap 当然

    【讨论】:

      【解决方案3】:

      您也可以使用[buttonInstance sizeToFit]

       UIButton *lineButton = [[UIButton alloc] initWithFrame:CGRectZero];
       // If padding equals "yes, please"
       [lineButton setContentEdgeInsets:UIEdgeInsetsMake(0.0f, 5.0f, 0.0f, 3.0f)];
       [lineButton setTitle:@"Title" forState:UIControlStateNormal];
       [lineButton sizeToFit];
      

      【讨论】:

        猜你喜欢
        • 2018-04-03
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 2023-04-02
        • 1970-01-01
        • 2022-11-29
        相关资源
        最近更新 更多