【问题标题】:Place UIButton with dynamic tex at the center of UITableViewCell将带有动态 tex 的 UIButton 放在 UITableViewCell 的中心
【发布时间】:2015-03-07 11:47:05
【问题描述】:

我在表格单元格中有一个UIButton。我想将按钮放在单元格的中心。按钮的文本是动态的。这是我尝试过的,但它不是在中心。它正在向中心的右侧移动。

UIButton *btnName = [UIButton buttonWithType:UIButtonTypeRoundedRect];

CGSize maximumLabelSize = CGSizeMake(self.frame.size.width, MAXFLOAT);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;

NSDictionary *attr = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
CGRect labelBounds = [titleText boundingRectWithSize:maximumLabelSize
                                             options:options
                                          attributes:attr
                                             context:nil];
CGFloat width = ceilf(labelBounds.size.width);

btnName.frame = CGRectMake(0.0, imgPic.frame.origin.y+imgPic.frame.size.height+20.0, width, 20.0);
btnName.center = CGPointMake(cell.contentView.center.x, imgPic.frame.origin.y+imgPic.frame.size.height+10.0);

[btnName setTitle:titleText forState:UIControlStateNormal];
[btnName setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[cell.contentView addSubview:btnName];

【问题讨论】:

  • 你试过btnName.center = cell.contentView.center 吗?您可能还想在设置按钮标题后进行居中。
  • @Zhang :是的,我试过了,但没用。
  • @WorldOfWarcraft:我是否也需要设置中心和框架。如果你能发布你的答案会有所帮助。
  • 你想把按钮放在单元格的中心吗?还是单元格的内容视图?它们完全不同。
  • @WorldOfWarcraft:在水平中心。

标签: ios iphone uibutton


【解决方案1】:

只需在代码中添加以下行。

btnName.center = cell.center;

【讨论】:

    【解决方案2】:

    您的代码看起来不错,只有您需要进行这些更改,

    1. 您应该在添加单元格后将按钮居中,并且

    2. 修正中心点


    [cell.contentView addSubview:btnName];
    
    btnName.center = CGPointMake(cell.frame.size.width/2.f, btnName.center.y);
    

    【讨论】:

      【解决方案3】:

      Vladimir's 回答拯救了我的一天。我使用了 setAutoresizingMask,现在一切正常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多