2016-10-01 44 views
-1

所以我到了這個地步,我基於從JSON返回的數組量來編程創建UIViews。除了應該爲每個視圖添加水龍頭的循環之外,一切似乎都會好起來,但它只是將其添加到一個視圖中。只打印最後一個UIView。循環UITapGestureRecognizer只添加到最後一個不是全部

func addsubviews(howmany: Int) -> Void{ 
    let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap")) 

for x in 1...howmany{ 

    guard let v = UINib(nibName: "DealsView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? UIView else { return } 

    v.translatesAutoresizingMaskIntoConstraints = false 
    guard let lbl = v.viewWithTag(99) as? UILabel else { return } 
    lbl.text = "Here is a new Label for Loop: " + "\(x)" 

    self.allContainer.addSubview(v) 

    v.backgroundColor = UIColor.white 

    var horizontalConstratint1 = NSLayoutConstraint() 
    var horizontalConstratint2 = NSLayoutConstraint() 
    var verticalConstraint1 = NSLayoutConstraint() 

    heightConstraint = v.heightAnchor.constraint(equalToConstant: 100) 
    horizontalConstratint1 = v.leadingAnchor.constraint(equalTo: (v.superview?.leadingAnchor)!, constant: 10) 
    horizontalConstratint2 = v.trailingAnchor.constraint(equalTo: (v.superview?.trailingAnchor)!, constant: -10) 

    if prevView == nil{ 
     verticalConstraint1 = v.topAnchor.constraint(equalTo: (v.superview?.topAnchor)!, constant: 20) 
     }else 
    { 
     if let pv = prevView as? UIView { 
      verticalConstraint1 = v.topAnchor.constraint(equalTo: (pv.bottomAnchor), constant: 20) 
     } 
    } 
    NSLayoutConstraint.activate([horizontalConstratint1,horizontalConstratint2,verticalConstraint1]) 

    prevView = v 
     } 

    if let pv = prevView as? UIView { 
     print("final constratint") 
     NSLayoutConstraint.activate([ 
      self.allContainer.bottomAnchor.constraint(equalTo: pv.bottomAnchor, constant: 20) 
      ]) 
    } 

    for views in self.allContainer.subviews{ 
     print("adding views") 
     views.addGestureRecognizer(tap) 
    } 

} 

一些試驗和錯誤後...

添加到每個循環的自來水識別:

 let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(sender:))) 

這將是那裏的行動繼續水龍頭的動作:

func handleTap(sender: UITapGestureRecognizer) { 
    // You can get the view here by writing 
    let myv = sender.view 
    print(myv) 
} 

回答

1

在您的視圖循環開始之前,您只有一個UITapGestureRecognizer。 AFAIK,輕拍手勢識別器一次只能附加到一個視圖。檢查出this question。爲了解決這個問題,請嘗試寫下這一行:

let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap")) 

在你的視圖循環中。


要找出被竊聽什麼看法,讓你選擇 handleTap帶任何參數,像這樣:

Selector("handleTap:") 

和方法本身是這樣的:

func handleTap(sender: UITapGestureRecognizer? = nil) { 
    // You can get the view here by writing 
    let v = sender.view 
} 
+0

就是爽...工作...只是想知道如何我可以識別UIVIew是挖掘什麼....我想有一個模式窗口出現,並根據什麼UIVIEW挖掘電話數據 – BostonMacOSX

+0

akshit我得到:2016-10-01 19 :26:56.092 JSONTesting [15648:1330158] - [JSONTest ing.DealsController handleTap:]:無法識別的選擇器發送到實例0x7fccb0e0a9d0上面更新的代碼..... – BostonMacOSX

+0

如果您使用的是swift 2.2,選擇器語法如下所示:#selector(MyControllerName.handleTap(_ :)),我認爲這就是導致這個錯誤的原因。 – aksh1t

相關問題