Q:get 视图约束 returns 空数组

Q:get a view's constrains returns empty array

首先我展示我的 cell ,我的标签有几个 constaints:



在我的 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 方法中。

我得到了 label 的约束:

NSArray *cons = (((NoticeAnnouncementCell*)cell).mainTitle).constraints;

但我得到一个空数组。

也许您需要从 superView 获取约束?

NSArray *constraints = cell.constraints;

在子视图中查找约束

NSArray *subviews = cell.subviews;

[subviews enumerateObjectsUsingBlock:^(UIView  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
   if (obj.constraints.count == 0) {
      return;
   }

   NSLog(@"%@", obj);
   NSLog(@"%@", obj.constraints);

}];

你应该先创建一个cell实例,然后访问label的约束,

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell1 = (UITableViewCell*) [tableView cellForRowAtIndexPath:indexPath];
    UILabel *label = (UILabel*) [cell viewWithTag:10];
    NSArray *arrayOfLableConstraint = [label constraints];

}

通过这种方式,您将获得仅设置为标签本身的约束,如宽度和高度或任何对齐约束,以获得您应该访问单元格约束的所有约束,不用担心如何仅查找标签约束对于其他视图,您只需为标签设置的约束设置标识符即可轻松做到这一点。

您可以将标识符设置为约束,只需单独选择约束并从尺寸检查器中设置标识符,如下所示,

希望对你有所帮助...