2017-01-25 98 views
-1

我有自定義視圖,應該點擊並執行一些操作。 我在同一屏幕上有兩個CustomView。我想要檢測哪個被點擊做不同的動作。檢測哪個uview被觸摸

是否可以在那裏設置一些ID來檢測哪個被準確點擊?

這裏是我的CustomView

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() 
    } 
} 

回答

1

如果你想使用委託,那麼你應該改變你的委託功能,這樣的觀點提供了一個參考,以自己的委託。

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) 
    } 

} 

然後在你的委託功能,您可以以採取適當的行動比較傳遞的引用或其他財產的價值:

func costomView(clicked: CostomView) { 
    if clicked == self.costomView1 { 
     // Do something 
    } else if clicked == self.costomView2 { 
     // Do something else 
    } 
} 

您還可以將屬性添加到您的CostomView類當視圖被點擊時,持有閉包並調用閉包。這也許是一種更「現代化」的方式,但代表團仍然有效,你是如何做的是一個意見問題。就我個人而言,我認爲代表團的一個優點是在查看代碼時可以快速找到類中的委託函數,而閉包可能不那麼明顯。

+0

非常感謝您的回答,它真的幫助了我。我認爲'現代'的方式是使用代表團,你可以給我一個'hold closure和invoke closure'的例子鏈接嗎?我真的沒有明白這是什麼意思。 – pmb

0

做到這一點的最佳方式 - 爲您的CostomView定義觸摸行爲,例如使用閉包的父類或視圖控制器。最快的(但相當醜陋)的方式 - 爲這些視圖設置不同的標籤,併爲不同的標籤編寫不同的行爲。