在我的 viewWillAppear() 中,我创建了一个标签并给它一个标签。当满足另一个条件时,我尝试删除标签,但由于某种原因,它不起作用并且标签仍在视图中。我一定做错了什么...
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var label: UILabel?
// Add label if there are no recipes
if (recipeBook.recipesArr.count == 0) {
label = self.view.viewWithTag(123) as? UILabel
//label?.tag = 123 // arbitrary num
label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100))
label?.text = "Add A Recipe"
label?.textColor = UIColor(red:0.93, green:0.92, blue:0.92, alpha:1.0)
label?.font = label?.font.withSize(36)
label?.textAlignment = .center
self.view.addSubview(label!)
}
else {
// remove it
if let foundLabel = self.view.viewWithTag(123) {
foundLabel.removeFromSuperview()
} else {
print("Couldn't find label with tag in view")
}
}
}
我没有意识到在这一行中label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100))
我正在创建一个默认标签为 0 的新标签。将其更改为label?.frame = CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100)
以便我不创建新标签并且一切正常。愚蠢的错误。