我有一个UILabel,我已经通过编程制作成:

var label = UILabel()

然后我为标签声明了一些样式,包括字体,例如:

label.frame = CGRect(x: 20, y: myHeaderView.frame.height / 2, width: 300, height: 30)
label.font = UIFont(name: "Typo GeoSlab Regular Demo", size: 15)
label.textColor = UIColor(hue: 0/360, saturation: 0/100, brightness: 91/100, alpha: 1)

标签的第一部分始终为:"Filter:",然后是字符串的另一部分,例如,"最受欢迎"

我希望单词过滤器是粗体的,所以整个东西看起来像:

Filter:最受欢迎

我想用最简单的方法来创造效果.我一直在互联网上搜索如何实现这一点,有很多方法,有些看起来就像一页页的代码.其中大部分似乎都是Objective-C.我想用Swift:)

我不知道我是否在正确的路由上,但这是NSRange能帮助实现的吗?提前谢谢

Update

我使用一系列if条语句来更改label变量.例如:

if indexArray == 1 {

    label.text = "Filter: Film name"

} else if indexArray == 2 {

    label.text = "Filter: Most popular"

} else if indexArray == 3 {

    label.text = "Filter: Star rating"

}

推荐答案

你需要使用attributedString,它允许你对字符串的某些部分进行样式设置.这可以通过使用两种样式来实现,一种是普通样式,一种是粗体样式,然后将它们连接在一起:

let boldText = "Filter:"
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]
let attributedString = NSMutableAttributedString(string:boldText, attributes:attrs)

let normalText = "Hi am normal"
let normalString = NSMutableAttributedString(string:normalText)

attributedString.append(normalString)

要将其指定给标签时:

label.attributedText = attributedString

Swift相关问答推荐

我应该在自定义存储队列上使用弱self 吗?

防止NavigationLink自行返回导航视图

为什么不能使用actor作为AsyncSequence中的状态机类型?

如何更新Square Order?

按Esc键时执行操作(工作表)

RealityKit(VisionOS)中的PhysicBodyComponent和DragGesture

是否可以使用一个 NSRegularExpression 同时判断字符串格式并提取子字符串?

使用索引来访问 libc 定义的元组

Swift Random Float Fatal Error:在无限范围内没有均匀分布

如何判断一个值是否为 Int 类型

为 ObservedObject 和 State 对象配置预览

如何有条件地依赖桌面与 iOS 的系统库?

Swift中的分段错误

将if let与逻辑或运算符一起使用

无法分配给属性:self 是不可变的,我知道如何修复但需要理解

获取设备图像比例(例如@1x、@2x 和@3x)

如何轻松删除领域中的所有对象

playground 导入:没有这样的模块Foo

将活动指示器 colored颜色 更改为黑色

来自 ObservableObject 的绑定值