首页
学习
活动
专区
工具
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)

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

相关·内容

  • 史上最全的iOS之UITextView实现placeHolder占位文字的N种方法

    iOS开发中,UITextField和UITextView是最常用的文本接受类和文本展示类的控件。UITextField和UITextView都输入文本,也都可以监听文本的改变。不同的是,UITextField继承自UIControl这个抽象类。UITextView继承自UIScrollView这个实体类。这就导致了UITextView可以多行展示内容,并且还可以像UIScrollView一样滚动。而UITextField只能单独的展示一行内容。从这个角度,UITextView在功能上是优于UITextField的。 但是,众所周知,UITextField中有一个placeholder属性,可以设置UITextField的占位文字,起到提示用户输入相关信息的作用。可是,UITextView就没那么幸运了,apple没有给UITextView提供一个类似于placeholder这样的属性来供开发者使用。而开发中,我们经常会遇到既要占位文字,又要可以多行展示并且可以滚动的控件,单纯的UITextField或者UITextView都不能满足这种产品上的需求。比如,现在市面上的app大多都有一个用户反馈的入口,如下图(一)所示。下面我就把自己能够想到的方法汇总一下,让更多的开发者知道,原来有这么多方法可以实现UITextView的占位文字。

    04
    领券