主要涉及到助记词的排序自适应
这里把主要代码贴出来
// MARK: - 多个不同宽度button自动换行
func createViewWithTitleArr(_ titleAry: Array<Any>?) {
while (mBgView.subviews.count > 0) {
let child = mBgView.subviews.last
child?.removeFromSuperview()
}
var pointX: CGFloat = 10.0 //button X坐标
var pointY: CGFloat = 10.0 //button Y坐标
let padding: CGFloat = 12.0 //button 间距
let btnHeight: CGFloat = 27.0 //button 高度
let allWidth = mBgView.frame.size.width
let mCount: Int = (titleAry?.count)!
for i in 0..<mCount {
let mTitle: String = titleAry![i] as! String
let constraint = CGSize(width: CGFloat(MAXFLOAT), height: 30)
let rect = mTitle.boundingRect(with: constraint, options:[.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14)], context: nil)
let btnWidth = rect.width + 20
if pointX + btnWidth > allWidth {
pointX = 10.0//X重新开始
pointY += (btnHeight + padding)//换行后Y+
}
let but = UIButton(type: UIButton.ButtonType.custom)
but.frame = CGRect.init(x: pointX, y: pointY, width: btnWidth, height: btnHeight)
but.tag = i + 1000;
but.addTarget(self, action: #selector(clickButtonAction(sender:)), for: .touchUpInside)
but.layer.masksToBounds = true
but.layer.cornerRadius = 1
but.backgroundColor = RGB(250, 234, 222)
but.setTitle(mTitle, for: .normal)
but.setTitleColor(RGB(51, 51, 51), for: .normal)
but.titleLabel?.font = UIFont.systemFont(ofSize: 14)
pointX += (btnWidth + padding);//每次X都加上button宽和间距12
mBgView.addSubview(but)
}
if pointY + btnHeight + 10 < 135 {
mBgViewHeight.constant = 135
}else {
mBgViewHeight.constant = pointY + btnHeight + 10
}
}