2017-11-25 64 views
0

我以編程方式創建了許多UI元素。比方說50個UILabels。 什麼是訪問標籤屬性的正確方法? 現在,我通過「發送」加入標籤,在[子視圖]數組,並獲得標註屬性每個標籤和下一個搜索標籤:引用以編程方式創建的UI元素

func buttonTapped(sender: UIButton) { 

     for subview in containerView.subviews { 

      if let label = subview as? UILabel, label.tag == sender.tag { 
// do stuff 
} 
} 
} 

不知道這是最優雅的方式,因爲有一些問題,如果我們將標籤更改爲按鈕。

比方說:

func createButton() { 
    let button = UIButton(frame: CGRect(origin: ..., 
             size: ...)) 

    button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) 

    let longTap = UILongPressGestureRecognizer(target: self, action: #selector(disableButton(sender:))) 
    longTap.minimumPressDuration = 1 
    button.addGestureRecognizer(longTap) 

    ....... 
    containerView.addSubview(button) 

} 

,現在我不能disableButton(發件人:)方法通過「發件人」訪問屬性,因爲發件人是UILongPressGestureRecognizer。

似乎我做錯了,如果它適用於標籤,但不適用於按鈕。 請,引導我在正確的方向

回答

0

首先,我會保留並列出所有標籤的引用,這樣您就不必遍歷所有子視圖來查找它們,並按照z值最高的順序排列。但是,如果你不想這樣做,那麼你可以在一行中查看代碼;它不是世界上最有效率的東西,但對於你的數字來說它應該沒問題。

class ViewController: UIViewController { 
    let first = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) 
    let second = UILabel(frame: CGRect(x: 25, y: 25, width: 100, height: 50)) 
    override func viewDidLoad() { 
     first.text = "first" 
     first.backgroundColor = .blue 
     second.text = "second" 
     second.backgroundColor = .red 
     view.addSubview(first) 
     view.addSubview(second) 
     let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))) 
     view.addGestureRecognizer(tap) 
    } 
    @objc func handleTap(sender: UITapGestureRecognizer) { 
     if let label = view.subviews.flatMap({$0 as? UILabel}).last(where: { $0.bounds.contains(sender.location(in: $0))}) { 
      print("You pressed: \(label)") 
     } 
    } 
} 

注意什麼回事:

  1. 我們使用flatMap丟棄不UIlabels任何子視圖。
  2. 我們使用last來查找數組中的最後一項( ,因爲根據UIView.subviews,最上面的視圖是最後一個視圖)觸摸位於視圖邊界內。
0

簡單添加此代碼,當你創建標籤

yourLbl.isUserInteractionEnabled = true 

並使用的touchesBegan方法,讓您的點擊標籤

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    let touch = touches.first 
    if let lblView = touch?.view 
    { 
     if lblView.isKind(of: UILabel.self) 
     { 
      let yourLbl = lblView as! UILabel 

      //Access your clicked lable 
     } 
    } 


} 
+0

但是長時間敲擊怎麼辦?我碰到沒有問題只是觸摸 – drywet

+0

長期按[長按]這個鏈接(https://stackoverflow.com/questions/45243947/uilabel-long-press-gesture-for-menu-item-of-uimenucontroller) –