Ios 检测触摸了哪个uiview
我有自定义视图,应该单击它并执行一些操作。 我在同一屏幕上有两个CustomView。我想检测单击哪个按钮执行不同的操作 是否可以在那里设置一些ID来检测到底单击了哪个ID 这是我的看法Ios 检测触摸了哪个uiview,ios,swift,uiview,Ios,Swift,Uiview,我有自定义视图,应该单击它并执行一些操作。 我在同一屏幕上有两个CustomView。我想检测单击哪个按钮执行不同的操作 是否可以在那里设置一些ID来检测到底单击了哪个ID 这是我的看法 protocol CostomViewDelegate: class { func viewClicked() } class CostomView: UIView, UIGestureRecognizer { @IBOutlet weak var placeholderlbl: UILa
protocol CostomViewDelegate: class {
func viewClicked()
}
class CostomView: UIView, UIGestureRecognizer {
@IBOutlet weak var placeholderlbl: UILabel!
@IBOutlet weak var textLbl: UILabel!
weak var delegate: CostomViewDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.layer.backgroundColor = UIColor.red.cgColor
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.layer.backgroundColor = UIColor.white.cgColor
delegate?.viewClicked()
}
}
协议CostomViewDelegate:类{
func viewClicked()
}
类CostomView:UIView、UIGestureRecognitor{
@IBL:UILabel!
@IBL弱var textLbl:UILabel!
弱var委托:CostomViewDelegate?
覆盖func TouchesBegind(Touchs:Set,带有事件:UIEvent?){
self.layer.backgroundColor=UIColor.red.cgColor
}
覆盖功能触摸移动(touchs:Set,带有事件:UIEvent?){
}
覆盖函数touchesend(touchs:Set,带有事件:UIEvent?){
self.layer.backgroundColor=UIColor.white.cgColor
委托?.viewClicked()
}
}
如果要使用委派,则应更改委派函数,以便视图向委派提供对自身的引用
protocol CostomViewDelegate: class {
func costomView(clicked: CostomView)
}
class CostomView: UIView, UIGestureRecognizer {
@IBOutlet weak var placeholderlbl: UILabel!
@IBOutlet weak var textLbl: UILabel!
weak var delegate: CostomViewDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.layer.backgroundColor = UIColor.red.cgColor
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.layer.backgroundColor = UIColor.white.cgColor
delegate?.costomView(clicked: self)
}
}
您还可以向
CostomView
类中添加一个属性,该属性保存闭包,并在点击视图时调用该闭包。这也许是一种更“现代”的方法,但授权仍然有效,如何授权是一个意见问题。就我个人而言,我认为委派的一个优点是,在查看代码时,您可以在类中快速找到委派函数,而闭包可能不太明显。最好的方法是从父类或视图控制器(例如闭包)定义CostomView
的触摸行为。最快的(但相当难看)方法-为这些视图设置不同的标记,并为不同的标记编码不同的行为。非常感谢您的回答,它确实帮助了我。我认为“现代”的方式是使用委托,你能给我发一个“holds closure和invoke closure”的示例链接吗?我真的不明白那是什么意思。
func costomView(clicked: CostomView) {
if clicked == self.costomView1 {
// Do something
} else if clicked == self.costomView2 {
// Do something else
}
}