所以我要根据从 JSON 返回的数组的数量以编程方式创建 UIView。一切似乎都正常,除了应该将水龙头添加到每个 View 的循环,但它只将它添加到一个 View 。仅在最后一个 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)
}
最佳答案
在 View 循环开始之前,您只有一个 UITapGestureRecognizer
。 AFAIK,点击手势识别器一次只能附加到一个 View 。查看this question .要解决这个问题,请尝试编写以下行:
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
在你的 View 循环中。
要找出点击了哪个 View ,请让您的选择器
handleTap
接受如下参数:
Selector("handleTap:")
方法本身是这样的:
func handleTap(sender: UITapGestureRecognizer? = nil) {
// You can get the view here by writing
let v = sender.view
}
关于swift - 循环 UITapGestureRecognizer 只添加到最后一个而不是全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809311/