ios - 我应该把 AutoLayout 代码放在哪里?
<p><p>我正在使用 <code>PureLayout</code> 来实现 UIView 中 subview 的 AutoLayout。但我不知道组织代码的最佳实践。</p>
<p>应该把AutoLayout相关的代码放在UIView的<em>init</em>中,还是<code>updateConstraints</code>和<code>layoutSubviews</code>等重写方法?</code> p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>比如我想创建一个UIView的子类叫PHView,对于任何一个phview,都有一个叫centerView的子view,它总是在phview的中心,width/height是0.3*phview的width/height。
<a href="https://www.dropbox.com/s/jaljggnymxliu1e/IMG_3178.jpg" rel="noreferrer noopener nofollow">https://www.dropbox.com/s/jaljggnymxliu1e/IMG_3178.jpg</a> </p>
<pre><code> #import "PHView.h"
#import "Masonry.h"
@interface PHView()
@property (nonatomic, assign) BOOL didUpdateConstraints;
@property (nonatomic, strong) UIView *centerView;
@end
@implementation PHView
- (instancetype)init {
self = ;
if (self) {
self.backgroundColor = ;
self.translatesAutoresizingMaskIntoConstraints = NO;
}
return self;
}
- (UIView *)centerView {
if (!_centerView) {
_centerView = ;
_centerView.backgroundColor = ;
;
}
return _centerView;
}
-(void)updateConstraints {
if (!_didUpdateConstraints) {
_didUpdateConstraints = YES;
[self.centerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.mas_centerX);
make.centerY.equalTo(self.mas_centerY);
make.width.equalTo(self.mas_width).multipliedBy(0.3);
make.height.equalTo(self.mas_height).multipliedBy(0.3);
}];
}
;
}
@end
</code></pre>
<p>'didUpdateConstraints' 旨在表明您已添加约束,因此您只会添加一次约束。</p>
<p>在 UIViewController:make phview top left bottom right 20 to margin.</p>
<pre><code>- (void)viewDidLoad {
;
self.view.backgroundColor = ;
PHView *myView = ;
;
[myView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(20, 20, 20, 20));
}];
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 我应该把 AutoLayout 代码放在哪里?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/31376831/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/31376831/
</a>
</p>
页:
[1]