【发布时间】: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:在水平中心。