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

本文介绍了如何在Swift中动态生成多个按钮,并让这些按钮的大小根据其显示的文字内容长度自动调整,以确保视觉效果的一致性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
            }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值