ios – UITextField中的Autolayout:执行-layoutSubviews后仍需要自动布局

我正在继承UITextField以在左侧添加标签.我正在使用autolayout来布局标签.但是,我一直在崩溃:

这是我如何做我的布局代码

- (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子类中布局子视图,设置它们的属性,移动它们等,但从未明确地告诉视图自行解决(即调用[self layoutIfNeeded]).

iOS 8似乎强制要查看布局其所有子视图,然后在其上配置约束. iOS 7不会,并且如果您正在使用自动布局,则需要您在更改时明确告知视图重绘其子视图.

在我的例子中,我已经将UITextField子类化,并在侧面添加一个标签.我通过向UITextfield添加约束来配置标签的框架.我可以在班上打电话的一种公共方法

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

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

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

每次更改子类中视图的一部分时都需要调用它.这包括添加子视图时的设置,更改视图属性时的设置.在更改视图返回的函数返回之前,请在视图上调用layoutIfNeeded.这似乎适用于一些标准的UI控件,包括UITextfield,UITableView和UICollectionView,虽然我确定还有其他的.我希望这很清楚,并帮助解决你的问题.

你得到的错误并不是非常有用,甚至不适用于我的情况.虽然我收到了完全相同的错误,但是我的所有视图都没有实现layoutSubviews,因此都使用了[super layoutSubviews]方法.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...