[英]How can i reset UIlabel attributes to default settings in swift
I created a UIlabel
named etiket . 我创建了一个UIlabel
名为ETIKET。 then I created an action button and I made changes like color change on it. 然后我创建了一个动作按钮,并对其进行了更改,例如颜色更改。 it's a sample: 这是一个示例:
@IBAction func changeColor(_ sender: Any) {
etiket.textColor = UIColor.red
then I created again an action button and now when I pressed the button I want to reset UIlabel
to default settings. 然后我再次创建了一个动作按钮,现在按下按钮时,我想将UIlabel
重置为默认设置。
I tried this method 我尝试过这种方法
@IBAction func sifirla(_ sender: Any) {
etiket.text = "nil"
when I tried this method UIlabel
completely disappeared. 当我尝试此方法时, UIlabel
完全消失了。
How can I reset UIlabel
attributes to default settings? 如何将UIlabel
属性重置为默认设置? I did some research, but I could not find exactly what I wanted. 我做了一些研究,但是找不到我想要的东西。
You need to create a label dynamically and assign a tag value to it. 您需要动态创建标签并为其分配标签值。
func createLabel() -> UILabel {
let lbl = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 55))
lbl.tag = 101
//set other properties of label
return lbl
}
In changeColor
method you need to get label by tag value and set its color. 在changeColor
方法中,您需要按标签值获取标签并设置其颜色。
@IBAction func changeColor(_ sender: Any) {
if let lbl = self.view.viewWithTag(101) as? UILabel {
lbl.textColor = UIColor.red
}
}
In sifirla
method you need to get label by tag value and remove it from its super view and create a new label and add it in your current view, so by adding a new UILabel instance you will get default settings of label. 在sifirla
方法中,您需要按标签值获取标签,并将其从其超级视图中删除,然后创建新标签并将其添加到当前视图中,因此,通过添加新的UILabel实例,您将获得标签的默认设置。
@IBAction func sifirla(_ sender: Any) {
if let lbl = self.view.viewWithTag(101) as? UILabel {
lbl.removeFromSuperview()
let newLbl = self.createLabel()
self.view.addSubview(newLbl)
}
}
Note: If you are using autolayout then you need to set constraint to label instead of frame. 注意:如果使用的是自动布局,则需要将约束设置为标签而不是帧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.