要使用NSMutableAttributedString设置UILabel的圆角背景,可以按照以下步骤进行操作:
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
label.text = "Hello World"
let attributedString = NSMutableAttributedString(string: label.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16),
.foregroundColor: UIColor.white,
.backgroundColor: UIColor.blue,
.cornerRadius: 10 // 设置圆角半径
]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
label.attributedText = attributedString
label.layer.cornerRadius = 10
label.layer.masksToBounds = true
完整的代码示例:
import UIKit
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
label.text = "Hello World"
let attributedString = NSMutableAttributedString(string: label.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16),
.foregroundColor: UIColor.white,
.backgroundColor: UIColor.blue,
.cornerRadius: 10 // 设置圆角半径
]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
label.attributedText = attributedString
label.layer.cornerRadius = 10
label.layer.masksToBounds = true
这样,你就可以使用NSMutableAttributedString设置UILabel的圆角背景了。
推荐的腾讯云相关产品:腾讯云移动推送(https://cloud.tencent.com/product/tpns)
领取专属 10元无门槛券
手把手带您无忧上云