草庐IT

ios - UITextField 中的自动布局 : Auto Layout still required after executing -layoutSubviews

coder 2023-09-21 原文

我将 UITextField 子类化以在左侧添加标签。我正在使用自动版式来布置标签。但是,我不断遇到此崩溃:

下面是我的布局代码:

- (void)updateConstraints {

self.segmentLabel.translatesAutoresizingMaskIntoConstraints = NO;

NSLayoutConstraint *constraint;
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0f];
[self addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0f];
[self addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0f];
[self addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.segmentWidth];
[self addConstraint:constraint];

[super updateConstraints];

当我不对文本字段进行任何调整时,它工作正常。

但是,如果我尝试设置占位符文本,则会出现此异常:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. DDSegmentedTextField's implementation of -layoutSubviews needs to call super.'

但是,我没有覆盖 -layoutSubviews。

有人遇到过吗?我做错了什么?

谢谢!

最佳答案

所以我几天前也遇到了同样的错误。结果我试图在我的 UITextfield 子类中布局 subview ,在它们上设置属性,移动它们等等,但从未明确告诉 View 自行布局(即调用 [self layoutIfNeeded]).

iOS 8 似乎强制 View 布局其所有 subview ,然后在其上配置约束。如果您使用自动布局,iOS 7 不会,并且需要您明确告诉 View 在您更改时重绘它们的 subview 。

在我的例子中,我对 UITextField 进行了子类化,并在旁边添加了一个标签。我通过向 UITextfield 添加约束来配置标签的框架。我可以在类里面调用的公共(public)方法之一是

- (void)setLabelText:(NSString *)newText{
    self.sideLabel.text = newText;
}

当出现包含我的子类文本字段的 View Controller 时,这导致我的应用程序崩溃。通过添加 layoutIfNeeded 现在在 iOS7 和 iOS8 中一切正常。

- (void)setLabelText:(NSString *)newText{
    self.sideLabel.text = newText;
    [self layoutIfNeeded];
}

每次更改子类中的 View 的一部分时都需要调用它。这包括添加 subview 时的设置,更改 View 属性时的任何设置。在改变 View 的函数返回之前,在 View 上调用 layoutIfNeeded。这似乎适用于一些标准的 UI 控件,包括 UITextfield、UITableView 和 UICollectionView,尽管我确信还有其他控件。我希望这已经足够清楚并有助于解决您的问题。

您遇到的错误不是很有用,甚至不适用于我的情况。虽然我收到了完全相同的错误,但我的 View 都没有实现 layoutSubviews,因此都使用了 [super layoutSubviews] 方法。

关于ios - UITextField 中的自动布局 : Auto Layout still required after executing -layoutSubviews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25573813/

有关ios - UITextField 中的自动布局 : Auto Layout still required after executing -layoutSubviews的更多相关文章

随机推荐