簡體   English   中英

無法找到帶有標簽的視圖

[英]unable to find view with tag

在我的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))意識到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)這樣我就不會創建新標簽,並且一切正常。 愚蠢的錯誤。

您的代碼沒有按照您的想法去做。 如果您的recipesArr為空(或更准確地說,計數為零),則嘗試查找帶有標簽123的標簽/視圖。然后將其忽略,然后創建一個新標簽,但不為其提供標簽。

您需要做的是在創建標簽后分配創建標簽的標簽,如下所示:

label?.tag = 123

然后,您將創建標簽並設置其標簽,以便隨后可以找到它。

您將在行label = UILabel(frame: CGRect之后重新創建標簽

您可以像這樣,以編程方式創建標簽,而無需選擇:

lazy var recipeLabel: UILabel = {
    let label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100))
    label.tag = 123
    label.text = "Add A Recipe"
    label.font = UIFont.systemFont(ofSize: 17.0)
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

然后根據需要將其添加到具有iOS 9+約束的子視圖中:

 self.view.addSubview(recipeLabel)

那么您可以通過簡單地引用視圖recipeLabel或訪問.tag屬性(如果需要)來訪問該視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM