在iOS中,有没有办法在一个标签中使用两种、甚至三种字体 colored颜色 ?

如果以文字"hello,are are you"为例,那么"hello"将是蓝色的,而"hello are you"将是绿色的.

这是可能的吗,这看起来比创建多个标签更容易吗?

推荐答案

Reference from here.

首先,初始化NSStringNSMutableAttributedString,如下所示.

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()

ViewDidLoad个月内

override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
    // set label Attribute
    labName.attributedText = myMutableString
    super.viewDidLoad()
}

OUTPUT

enter image description here

MULTIPLE COLOR

在ViewDidLoad中添加下面的行代码,以获得字符串中的多种 colored颜色 .

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

Multiple color OUTPUT

enter image description here

Swift 4

var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

Swift 5.0

 var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
 myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

Ios相关问答推荐

为什么导航栏在与Style.Page的选项卡栏一起使用时停止工作?

我应该使用哪个UIButton发送事件在SWIFT上刷卡?

SWIFT用户界面检测手势的开始和结束

如何在SwiftUI中为带有CornerRadius的矩形创建下边框?

确保方法调配的安全有效实施

如何制作支持不同语言的iOS应用

为什么这个 init 被分派到一个内部扩展 init?

为什么常量属性可能在 Swift 类中被初始化两次?

使用 AVCaptureDeviceTypeBuiltInTripleCamera 时 Select 合适的相机进行条码扫描

如何在 SwiftUI 中将选项卡放在滚动视图中?

过渡动画在 iOS16 中不起作用,但在 iOS15 中起作用

使用 Apollo 发布 iOS 应用程序时缺少推送通知权利

在所有 tableview / collectionview 中禁用滚动指示器

AVPlayer 退出全屏

使用 RxDatasources 作为数据源时如何填充自定义页眉/页脚视图

检测 iPhone/iPad/iPod touch 的 colored颜色 ?

UIScrollview 获取touch 事件

在 Xcode 5 中为超级视图添加间距约束

如何比较两个 UIImage 对象

SRCROOT 和 PROJECT_DIR 有什么区别?