[英]Get the size of UIButton inside a custom UITableViewCell with Autolayout
I have an UIButton inside a custom UITableViewCell created in Interface Builder, the height and width is defined by Autolayout constraints. 我在Interface Builder中创建的自定义UITableViewCell中有一个UIButton,其高度和宽度由自动布局约束定义。
I need to get the size of the UIButton after autolayout define the final size. 在自动布局定义最终大小后,我需要获取UIButton的大小。
what I have tried: 我尝试过的
Inside my custom UITableViewCell 在我的自定义UITableViewCell中
- (void)layoutSubviews
{
[super layoutSubviews];
NSLog(@"%f", self.infoButton.bounds.size.width);
self.infoButton.layer.cornerRadius = self.infoButton.bounds.size.width/2;
self.infoButton.clipsToBounds = YES;
self.infoButton.layer.borderColor = [UIColor whiteColor].CGColor;
self.infoButton.layer.borderWidth = 4.0f;
}
The problem is that I have different values : 问题是我有不同的值:
2015-06-30 03:01:47.578 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:47.581 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:47.583 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:47.585 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:47.586 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:47.586 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:53.482 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:53.484 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:54.939 MYPROJ[3596:34092] 56.000000
2015-06-30 03:02:04.161 MYPROJ[3596:34092] 56.000000
2015-06-30 03:02:05.115 MYPROJ[3596:34092] 56.000000
2015-06-30 03:02:05.957 MYPROJ[3596:34092] 56.000000
I have also tried the code inside - (void)awakeFromNib
I tried both self.infoButton.bounds.size.width
and self.infoButton.frame.size.width
我还尝试了内部代码
- (void)awakeFromNib
我尝试了self.infoButton.bounds.size.width
和self.infoButton.frame.size.width
and it gives me the static width before Autolayout which is in my case 48.0 Also 它为我提供了自动布局前的静态宽度,在我的情况下为48.0
I am afraid the solution of putting the code inside - (void)layoutSubviews
can affect performance since it will be called everything the user scroll and apply the layer transformation every time, is there any better solution ? 恐怕将代码放入
- (void)layoutSubviews
的解决方案会影响性能,因为每次用户滚动并应用图层转换都将调用它,是否有更好的解决方案?
In your custom UITableViewCell.m file, add following lines in your awakeFromNib method. 在您的自定义UITableViewCell.m文件中,在awakeFromNib方法中添加以下行。
Here, as your button is dependent on cell and which indeed has same width as device's screen. 在这里,您的按钮取决于单元格,并且其宽度实际上与设备的屏幕相同。
- (void)awakeFromNib {
// Initialization code
self.infoButton.layer.cornerRadius = [UIScreen mainScreen].bounds.size.width * 0.075f; // 0.15/2 = 0.075f (Half of the button's width)
self.infoButton.clipsToBounds = YES;
self.infoButton.layer.borderColor = [UIColor whiteColor].CGColor;
self.infoButton.layer.borderWidth = 4.0f;
}
Hope it helps... 希望能帮助到你...
尝试访问按钮的固有内容大小。
CGSize buttonSize = self.infoButton.intrinsicContentSize;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.