ios - 如何快速将 UIlabel 属性重置为默认设置
<p><p>我创建了一个名为 <strong>etiket</strong> 的 <code>UIlabel</code>。然后我创建了一个操作按钮,并对其进行了颜色更改等更改。这是一个示例:</p>
<pre><code>@IBAction func changeColor(_ sender: Any) {
etiket.textColor = UIColor.red
</code></pre>
<p>然后我再次创建了一个操作按钮,现在当我按下按钮时,我想将 <code>UIlabel</code> 重置为默认设置。</p>
<p>我试过这个方法</p>
<pre><code>@IBAction func sifirla(_ sender: Any) {
etiket.text = "nil"
</code></pre>
<p>当我尝试这个方法时<code>UIlabel</code>完全消失了。</p>
<p>如何将 <code>UIlabel</code> 属性重置为默认设置?
我做了一些研究,但找不到我想要的。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您需要动态创建标签并为其分配标签值。</p>
<pre><code>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
}
</code></pre>
<p>在 <code>changeColor</code> 方法中,你需要通过标签值获取标签并设置它的颜色。</p>
<pre><code>@IBAction func changeColor(_ sender: Any) {
if let lbl = self.view.viewWithTag(101) as? UILabel {
lbl.textColor = UIColor.red
}
}
</code></pre>
<p>在 <code>sifirla</code> 方法中,您需要按标签值获取标签并将其从其 superView 中删除并创建一个新标签并将其添加到当前 View 中,因此通过添加一个新的 UILabel 实例,您将获取标签的默认设置。</p>
<pre><code>@IBAction func sifirla(_ sender: Any) {
if let lbl = self.view.viewWithTag(101) as? UILabel {
lbl.removeFromSuperview()
let newLbl = self.createLabel()
self.view.addSubview(newLbl)
}
}
</code></pre>
<p>注意:如果您使用自动布局,则需要将约束设置为标签而不是框架。</p></p>
<p style="font-size: 20px;">关于ios - 如何快速将 UIlabel 属性重置为默认设置,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/47817998/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/47817998/
</a>
</p>
页:
[1]