在Swift中将UILabel设为粗体 [英] Make part of a UILabel bold in Swift

查看:486
本文介绍了在Swift中将UILabel设为粗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以编程方式制作的UILabel:

I have a UILabel I've made programmatically as:

var label = UILabel()

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

I've then declared some styling for the label, including a font, such as:

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:",然后是字符串的另一部分,例如"Most Popular"

The first part of the label will always read : "Filter:" then followed by another part of the string, for example, "Most popular"

我希望过滤器一词以粗体显示,所以整个过程看起来像这样:

I would like the word filter to be in bold, so the whole thing would look like:

过滤器:最受欢迎

我想以最简单的方式来创建这种效果.我一直在互联网上寻找如何实现这一目标的方法,而且有很多方法,有些方法看起来像是代码页.而且大多数似乎都在Objective-C中.我想要在Swift中使用它:)

I want to simplest way of creating this effect. I've been searching the internet for how to achieve this and there are so many ways, some which just look like pages of code. And most of it seems to be in Objective-C. I would like it in Swift please :)

我不知道我是否正确,但这是NSRange可以帮助实现的目标吗?预先感谢

I don't know if i'm on the right lines, but is this what NSRange can help achieve? Thanks in advance

更新

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

I use a series of if statements to change my label variable. Such as:

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,该样式允许您设置字符串等的样式.可以通过两种样式来完成此操作,一种是普通样式,一个粗体,然后将它们连接在一起:

You will want to use attributedString which allows you to style parts of a string etc. This can be done like this by having two styles, one normal, one bold, and then attaching them together:

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中将UILabel设为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆