首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何用NSMutableAttributedString设置UILabel (非UITextView)圆角背景?

要使用NSMutableAttributedString设置UILabel的圆角背景,可以按照以下步骤进行操作:

  1. 首先,创建一个UILabel实例,并设置其frame和文本内容。
代码语言:txt
复制
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
label.text = "Hello World"
  1. 创建一个NSMutableAttributedString实例,并设置其属性。
代码语言:txt
复制
let attributedString = NSMutableAttributedString(string: label.text ?? "")
  1. 使用NSAttributedString.Key设置NSMutableAttributedString的属性,包括字体、颜色、背景色等。
代码语言:txt
复制
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))
  1. 将NSMutableAttributedString应用到UILabel上。
代码语言:txt
复制
label.attributedText = attributedString
  1. 设置UILabel的圆角属性。
代码语言:txt
复制
label.layer.cornerRadius = 10
label.layer.masksToBounds = true

完整的代码示例:

代码语言:txt
复制
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)

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券