在 UITableviewCell 自动布局中获取 UIView 高度



我想根据设备cellForRowAtIndexPath方法获取UIViewA的实际宽度,并且"UIViewA"在自定义UITableViewCell中。我在UITableViewCell中使用自动布局。

my UIViewA in in Custom UITableViewCell, UITableviewCell Width = 384和我的 UITablVIewWidth = 284。所以我需要 UIViewA 宽度是 284 在单元格为行在索引路径

请指导我如何在cellForRowAtIndexPath获得UIView宽度,因为我想在UIView中添加动态内容。

怎么样

cell.UIViewA.frame.size.width

cell.UIViewA.bounds

将其添加到单元格中的视图创建中

UIView *backgroundView = [UIView new];
[backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];
[backgroundView setBackgroundColor:[UIColor grayColor]];
backgroundView.layer.cornerRadius = 5;
[self addSubview:backgroundView];

NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(backgroundView);

[NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[backgroundView]|"
                                                                                options:0
                                                                                metrics:nil
                                                                                  views:viewsDictionary]];
[NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[backgroundView]|"
                                                                                options:0
                                                                                metrics:nil
                                                                                  views:viewsDictionary]];

现在,您可以打印视图框并获取宽度。

通常,当您需要查阅视图的框架或边界并使用自动布局定位视图时,请首先执行以下操作:

[myView setNeedsLayout];
[myView layoutIfNeeded];

现在myView将有其正确的框架和边界。

最新更新