我已经创建了一个可重用的模态UIView作为单例对象,但是在更改它包含的标签文本时遇到了问题。当模式第二次出现时,新文本将显示在旧文本上。我猜这是因为标签只被实例化了一次?如果是这样,为什么我可以添加文本但不删除它?这是代码:
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
功能中的标签允许在模式的下一次出现时使用新文本重新实例化标签。
答案 0 :(得分:2)
正如kursus在评论中写道:你没有从父视图(实际模态视图)中删除按钮和标签作为子视图。如果再次出现,将创建两个新实例并将其放置在先前的实例上。我猜你只看到标签,因为它们基本上是透明的,按钮完全叠加。
要修复它,请在您的类中添加两个变量:
var button:UIButton!
var label:UILabel!
然后将modalInView
中的两行更改为
if label == nil {
label = UILabel(frame: CGRectMake(0, 0, 260, 100))
}
和
if button == nil {
button = UIButton(frame: CGRectMake(0, 0, 116, 50))
}
这将导致仅在之前未创建按钮和标签时才创建按钮和标签。
另一种方法是删除success
函数的dismiss
块中的两个视图,如
self.animateWithDuration(0.2, animations: { () -> Void in
self.modal.alpha = 0
}) { (Bool) -> Void in
self.modal.removeFromSuperview()
button.removeFromSuperview()
label.removeFromSuperview()
}