IOS开发中,总是有自适应高度布局的情况,如果想要获取某个自适应布局的View的高度的话,可以有两种方式:
- 调用layoutIfNeeded();
- 可以在主线程中获取;
1.假如在一个控制器中添加了一个contentView,想要获取contentView的高度:
func addSubviews() {
contentView = UIView()
contentView.backgroundColor = .gray
view.addSubview(contentView)
let titleLabel = UILabel()
titleLabel.text = "这是标题"
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textColor = .red
contentView.addSubview(titleLabel)
let detailLabel = UILabel()
detailLabel.text = "这是副标题"
detailLabel.font = UIFont.systemFont(ofSize: 14)
detailLabel.textColor = .red
contentView.addSubview(detailLabel)
let button = UIButton()
button.setTitle("按钮", for: .normal)
button.setTitleColor(.red, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
contentView.addSubview(button)
titleLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(10)
make.centerX.equalToSuperview()
}
detailLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(titleLabel.snp.bottom).offset(10)
}
button.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 100, height: 60))
make.top.equalTo(detailLabel.snp.bottom).offset(20)
make.bottom.equalToSuperview().offset(-20)
}
contentView.snp.makeConstraints { (make) in
make.left.right.bottom.equalToSuperview()
}
}
2.获取contentView的高度:
// 方法一
view.layoutIfNeeded()
print(contentView.frame.height)
// 方法二
DispatchQueue.main.async {
print(self.contentView.frame)
}