如何在 Swift 中更改 UILabel 的文本属性?



我已经以编程方式设置了一个UILabel,我正在尝试通过稍后在ViewController中调用的函数来更改文本属性,但是当该函数被称为questionLabel.text时,默认值为"欢迎"。

从本质上讲,我想要完成的是:

func changeLabelText() {
questionLabel.text = "New label text"
print(questionLabel.text!)
}
changeLabelText()
// prints "New label text"

但是我实际得到的是:

func changeLabelText() {
questionLabel.text = "New label text"
print(questionLabel.text!)
}
changeLabelText()
// prints "Welcome"

这是我的标签的设置方式:

class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
@IBOutlet var cameraView: UIView!
var questionLabel: UILabel {
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.backgroundColor = .white
label.textColor = .black
label.text = "Welcome"
label.textAlignment = .center
label.frame = CGRect(x: 65, y: 100, width: 300, height: 65)
return label
} 

有什么建议吗? 非常感谢!

当前

var questionLabel: UILabel { 
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.backgroundColor = .white
label.textColor = .black
label.text = "Welcome"
label.textAlignment = .center
label.frame = CGRect(x: 65, y: 100, width: 300, height: 65) 
return label 
} 

是一个计算属性,因此每次访问都会获得一个新的单独实例

questionLabel.text = "New label text" // instance 1
print(questionLabel.text!)   // instance 2

相反,你需要一个关闭

var questionLabel: UILabel = { 
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.backgroundColor = .white
label.textColor = .black
label.text = "Welcome"
label.textAlignment = .center
label.frame = CGRect(x: 65, y: 100, width: 300, height: 65) 
return label 
}()

将计算变量更改为惰性初始值设定项,如下所示:


lazy var questionLabel: UILabel = {
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.backgroundColor = .white
label.textColor = .black
label.text = "Welcome"
label.textAlignment = .center
label.frame = CGRect(x: 65, y: 100, width: 300, height: 65)
return label
}()

Klamont, 你可以试试这个。

假设您要更改标签的某些文本,您总是为此创建两个标签,但这是更改标签文本颜色的错误方法。 可以使用 NSMutableAttributedString 来更改标签的某些文本颜色。首先,您必须找到要更改该文本颜色的文本范围,然后将文本范围设置为与完整字符串相比的 NSMutableAttributedString 对象,然后使用 NSMutableAttributedString 对象设置标签 attributedText。

例:

let strNumber: NSString = "Hello Test" as NSString // you must set your  
let range = (strNumber).range(of: "Test")
let attribute = NSMutableAttributedString.init(string: strNumber)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range)
yourLabel.attributedText = attribute

如果你想在你的应用程序中多次使用它,你可以创建UILabel的扩展,它会变得更加简单:-

extension UILabel {
func halfTextColorChange (fullText : String , changeText : String ) {
let strNumber: NSString = fullText as NSString
let range = (strNumber).range(of: changeText)
let attribute = NSMutableAttributedString.init(string: fullText)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range)
self.attributedText = attribute
}
}

使用您的标签:-

yourLabel = "Hello Test"
yourLabel.halfTextColorChange(fullText: totalLabel.text!, changeText: "Test")

最新更新