Swift 如何创建N个按钮,并且控件大小随着获取的文字长度变化

nameList!.forEach { (text) in
                
                let attributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]
                var width = (text.name?.boundingRect(with: CGSize(width: Double(MAXFLOAT), height: height), options: NSStringDrawingOptions.usesFontLeading, attributes: attributes, context: nil).size.width)! + 30.0
                width = min(width, maxWidth)
                if (x + width) > (kScreenWidth - paddingLeft - 20.0) {
                    x = orginX
                    y = y + CGFloat(height) + lineSpace
                }
                let itemButton = UIButton(frame: CGRect(x: x, y: y, width: width, height: CGFloat(height)))
                itemButton.tag = tagNum
                itemButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15)
                itemButton.setTitle(text.name, for: .normal)
                itemButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                itemButton.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
                itemButton.setTitleColor(UIColorFromRGB(rgbValue: 0x666666), for: .normal)
                itemButton.backgroundColor = UIColorFromRGB(rgbValue: 0xECECEC)
                itemButton.layer.cornerRadius = CGFloat(height / 2.0)
                itemButton.layer.masksToBounds = true
                itemButton.addTarget(self, action: #selector(itemButtonAction(_:)), for: .touchUpInside)
                self.contentView.addSubview(itemButton)
                x = itemButton.frame.maxX + itemSpace
                tagNum += 1
            }

猜你喜欢

转载自blog.csdn.net/YY_Seven/article/details/88747274