所以我已经达到了基于从JSON返回的数组量以编程方式创建UIViews的程度。一切似乎都没问题,除了应该为每个视图添加点击的循环,但它只是将它添加到一个视图。仅打印在最后一个UIView上。
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)
}
答案 0 :(得分:2)
在视图循环开始之前,您只有一个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
}