簡體   English   中英

在自定義視圖中未調用UIButton操作

[英]UIButton action not called inside custom view

我要創建一個自定義視圖,其中將包含以下內容:

  • 綠景
  • 在綠色視圖內的圖像視圖
  • 在另一個白色視圖之上
  • 在白色視圖之上的另一個圖像視圖
  • 最重要的是

這是我的代碼,它位於自定義視圖中:

func setup() {

    // add green view
    let greenView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    greenView.backgroundColor = UIColor.greenColor()
    greenView.userInteractionEnabled = true
    addSubview(greenView)

    // add first image
    let image1 = UIImageView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    image1.image = UIImage(named: "checked2")
    image1.userInteractionEnabled = true
    greenView.addSubview(image1)

    // add white image
    let whiteView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    whiteView.backgroundColor = UIColor.yellowColor()
    whiteView.userInteractionEnabled = true
    greenView.addSubview(whiteView)

    // add second image
    let image2 = UIImageView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    image2.image = UIImage(named: "checked")
    image2.userInteractionEnabled = true
    whiteView.addSubview(image2)

    // add button
    let button = UIButton(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: Selector("animation:"), forControlEvents: UIControlEvents.TouchUpInside)
    button.userInteractionEnabled = true
    addSubview(button)



}

func animation(button: UIButton) {
    print("tapped")
}

紅色按鈕出現在頂部,但單擊該按鈕時不會調用該操作。
我試圖在所有元素上設置userInteractionEnabled ,但是沒有任何效果。

您發布的代碼運行正常,問題出在包含所有視圖的容器視圖中,也許userInteractionEnabled對於容器視圖為false。

默認情況下,按鈕用戶交互是打開的,無需顯式設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM