1、UIButton贴近右边,高度固定,宽度跟随标题变化
class TestButton: UIButton { } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let btn = TestButton(type: .custom) btn.setTitle("TestButton 1 2 3 sdasdad dadasd", for: .normal) btn.setTitleColor(.black, for: .normal) btn.layer.borderColor = UIColor.red.cgColor btn.layer.borderWidth = 1 view.addSubview(btn) btn.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-20) make.height.equalTo(30) } } }
效果:
2、限制宽度,多了就换行
class TestButton: UIButton { } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let btn = TestButton(type: .custom) btn.setTitle("TestButton 1 2 3 sdasdad dadasd,TestButton 1 2 3 sdasdad dadasd,TestButton 1 2 3 sdasdad dadasd", for: .normal) btn.setTitleColor(.black, for: .normal) btn.titleLabel?.numberOfLines = 0 btn.layer.borderColor = UIColor.red.cgColor btn.layer.borderWidth = 1 view.addSubview(btn) btn.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-20) // make.height.equalTo(30) make.width.lessThanOrEqualTo(200) } } }
效果:
明显,UIButton的框太小了,限制了titleLabel,现在想实现,button的高度和文字高度一样
修改如下
class TestButton: UIButton { override var intrinsicContentSize: CGSize { return titleLabel!.sizeThatFits(CGSize( titleLabel!.preferredMaxLayoutWidth, height: .greatestFiniteMagnitude)) } override func layoutSubviews() { titleLabel?.preferredMaxLayoutWidth = frame.size.width super.layoutSubviews() } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let btn = TestButton(type: .custom) btn.setTitle("TestButton 1 2 3 sdasdad dadasd,TestButton 1 2 3 sdasdad dadasd,TestButton 1 2 3 sdasdad dadasd", for: .normal) btn.setTitleColor(.black, for: .normal) btn.titleLabel?.numberOfLines = 0 btn.layer.borderColor = UIColor.red.cgColor btn.layer.borderWidth = 1 view.addSubview(btn) btn.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-20) // make.height.equalTo(30) make.width.lessThanOrEqualTo(200) } } }
效果:
总结:
Autolayout和intrinsicContentSize有关,UIButton的intrinsicContentSize默认和标题长短没有关系,和UILabel不一样