我創建了一個可重用的模態UIView作爲單例對象,但在更改其包含的標籤的文本時遇到了問題。當模式再次出現時,新文本將出現在舊文本上。我猜這是由於標籤僅實例化一次的事實?如果是這樣,那麼爲什麼我可以添加文本但不刪除它?這裏的代碼:當模態重新出現時,UILabel文本不會更新
class TransparentModal: UIView {
static let modal = TransparentModal()
class func modalInView(view: UIView, forSelectionOrPlacement: String) -> TransparentModal {
let f = CGRectMake(0, view.bounds.size.height, view.bounds.size.width, view.bounds.size.height)
modal.frame = f
modal.alpha = 0.7
modal.backgroundColor = UIColor.darkGrayColor()
let button = UIButton(frame: CGRectMake(0, 0, 116, 50))
button.center = CGPointMake(view.bounds.size.width/2, view.bounds.size.height/1.6)
button.backgroundColor = UIColor.lightGrayColor()
button.layer.cornerRadius = 4
button.setTitle("Ok", forState: UIControlState.Normal)
button.addTarget(self, action:"dismiss:", forControlEvents: UIControlEvents.TouchUpInside)
modal.addSubview(button)
let label = UILabel(frame: CGRectMake(0, 0, 260, 100))
label.center = CGPointMake(view.bounds.size.width/2, view.bounds.size.height/3)
label.numberOfLines = 0
label.text = ""
// This is where I'm going wrong
if forSelectionOrPlacement == "selection" {
label.text = "" // Attempting to remove previous text
label.text = "Text for condition one."
} else if forSelectionOrPlacement == "placement" {
label.text = ""
label.text = "Text for condition two."
}
modal.addSubview(label)
view.addSubview(modal)
self.animateWithDuration(0.5, animations: {() -> Void in
self.modal.frame.origin.y -= view.bounds.size.height
})
return modal
}
class func dismiss(sender: UIButton) {
self.animateWithDuration(0.2, animations: {() -> Void in
self.modal.alpha = 0
}) { (Bool) -> Void in
self.modal.removeFromSuperview()
}
}
}
我知道這是一個複雜的方式來創建一個簡單的模態。這更多的是創建可重用對象的練習。模態也需要出現在其他模態視圖,沒有導航控制器的視圖等,所以我想嘗試做出靈活的東西。
更新:下面的答案是正確的,只是變量只能作爲static
添加到類中。在dismiss
函數中刪除標籤允許標籤在模式下一次出現時用新文本重新實例化。
機會是你addSubview顯示視圖中的每個時間。您需要在init中添加它,或者每次在您的方法中刪除它。 – kursus