Masnory約束UIScrollerView
直接用Masonry對scrollView進(jìn)行約束,scrollView是不會(huì)滑動(dòng)的,因?yàn)榇_定不了contentSize。那么為什么繼承UIScrollerView的UITableView和UICollectionView沒有這種問題呢,可以發(fā)現(xiàn)他們的cell都有一個(gè)叫contentView的子視圖,我們自己添加的view 也都是加到contentView上邊的。
所以解決思路:給scrollView添加唯一的子視圖contentView,通過拉伸子視圖的size來確定scrollView的contentSize。
給contentView設(shè)置約束,注意:make.width.equalTo(self);這個(gè)約束必須要添加
self.contentView = [[UIView alloc] init];
self.contentView.backgroundColor = [UIColor clearColor];
[self addSubview:self.contentView];
[self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self);
//因?yàn)樯厦娴膶捀呤窍鄬τ赾ontentSize的 所以為0 這里需要設(shè)置contentView的寬度約束后 scrollView的contentSize.width就會(huì)拉伸
make.width.equalTo(self);
}];
還要注意一點(diǎn),在對contentView的最后一個(gè)子視圖添加約束的時(shí)候要加上make.bottom.equalTo(-20);這樣contentView才能確定scrollerView的contentSize,iOS8之后的tableView的cell高度自適應(yīng),設(shè)置tableView.estimatedRowHeight = 100;//一個(gè)估算值 之后,也是必須要對cell的子視圖的最后一個(gè)view加上距離底部的約束,才能實(shí)現(xiàn)cell高度自適應(yīng)
/// 說明文字
UILabel *lable = [UILabel labelWithText:@"使用說明:抵扣券可用于借款時(shí)抵扣手續(xù)費(fèi)\n積分可在商城中兌換禮品或者話費(fèi)" textFont:WGiveWidth(11) textColor:[LKTool colorWithHexString:@"#b996d9"] frame:CGRectZero];
[self.scrollerView.contentView addSubview:lable];
lable.textAlignment = 1;
lable.numberOfLines = 0;
// [lable setRowSpace:5];
[lable mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(btn.mas_bottom).offset(10);
make.width.equalTo(SCREEN_WIDTH);
make.centerX.equalTo(btn);
// 必須加上這個(gè)約束 這樣contentView才能確定scrollerView的contentSize
make.bottom.equalTo(-20);
}];
Masnory實(shí)現(xiàn)動(dòng)畫效果
在iOS開發(fā)中使用frame來動(dòng)畫更新控件frame是再熟悉不過的了:
[UIView animateWithDuration:0.5 animations:^{
view.frame = CGRectMake();
}];
但使用Masonry后,使用如下代碼來更新控件約束后,但無法看到控件位置更新的動(dòng)畫:
[UIView animateWithDuration:0.5 animations:^{
[view mas_updateConstraints:^(MASConstraintMaker *make) {
make.right.mas_equalTo();
}];
}];
正確的姿勢:
[self.alertView mas_updateConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self);
}];
// 告訴self.view約束需要更新
[self setNeedsUpdateConstraints];
// 調(diào)用此方法告訴self.view檢測是否需要更新約束,若需要?jiǎng)t更新,下面添加動(dòng)畫效果才起作用
[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.1 animations:^{
//使約束立即生效
[self layoutIfNeeded];
} completion:^(BOOL finished) {
// 動(dòng)畫結(jié)束之后處理
}];
后來發(fā)現(xiàn)不用調(diào)用setNeedsUpdateConstraints和updateConstraintsIfNeeded動(dòng)畫也是會(huì)生效的。
效果圖:
