Masnory約束UIScrollerView
直接用Masonry對(duì)scrollView進(jìn)行約束,scrollView是不會(huì)滑動(dòng)的,因?yàn)榇_定不了contentSize。那么為什么繼承UIScrollerView的UITableView和UICollectionView沒(méi)有這種問(wèn)題呢,可以發(fā)現(xiàn)他們的cell都有一個(gè)叫contentView的子視圖,我們自己添加的view 也都是加到contentView上邊的。
所以解決思路:給scrollView添加唯一的子視圖contentView,通過(guò)拉伸子視圖的size來(lái)確定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)樯厦娴膶捀呤窍鄬?duì)于contentSize的 所以為0 這里需要設(shè)置contentView的寬度約束后 scrollView的contentSize.width就會(huì)拉伸
make.width.equalTo(self);
}];
還要注意一點(diǎn),在對(duì)contentView的最后一個(gè)子視圖添加約束的時(shí)候要加上make.bottom.equalTo(-20);
這樣contentView才能確定scrollerView的contentSize,iOS8之后的tableView的cell高度自適應(yīng),設(shè)置tableView.estimatedRowHeight = 100;//一個(gè)估算值
之后,也是必須要對(duì)cell的子視圖的最后一個(gè)view加上距離底部的約束,才能實(shí)現(xiàn)cell高度自適應(yīng)
/// 說(shuō)明文字
UILabel *lable = [UILabel labelWithText:@"使用說(shuō)明:抵扣券可用于借款時(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)畫(huà)效果
在iOS開(kāi)發(fā)中使用frame來(lái)動(dòng)畫(huà)更新控件frame是再熟悉不過(guò)的了:
[UIView animateWithDuration:0.5 animations:^{
view.frame = CGRectMake();
}];
但使用Masonry后,使用如下代碼來(lái)更新控件約束后,但無(wú)法看到控件位置更新的動(dòng)畫(huà):
[UIView animateWithDuration:0.5 animations:^{
[view mas_updateConstraints:^(MASConstraintMaker *make) {
make.right.mas_equalTo();
}];
}];
正確的姿勢(shì):
[self.alertView mas_updateConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self);
}];
// 告訴self.view約束需要更新
[self setNeedsUpdateConstraints];
// 調(diào)用此方法告訴self.view檢測(cè)是否需要更新約束,若需要?jiǎng)t更新,下面添加動(dòng)畫(huà)效果才起作用
[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.1 animations:^{
//使約束立即生效
[self layoutIfNeeded];
} completion:^(BOOL finished) {
// 動(dòng)畫(huà)結(jié)束之后處理
}];
后來(lái)發(fā)現(xiàn)不用調(diào)用setNeedsUpdateConstraints
和updateConstraintsIfNeeded
動(dòng)畫(huà)也是會(huì)生效的。
效果圖: