2017-04-01 20 views
-4

我有裏面一個UIButton一個UIView但按鈕無法識別手勢的UIButton裏面一個UIView不響應的姿態

任何想法,爲什麼?我曾嘗試在與此相關的問題中使用解決方案,但尚未成功。

全班代碼:

import UIKit 
import Foundation 

public class HUDView: UIView , UIGestureRecognizerDelegate { 
    var stopwatch: StopwatchView 
    var gamePoints: CounterLabelView 

    var hintButton: UIButton! 

    required public init(coder aDecoder: NSCoder) { 
     fatalError("Never call this... Use init(frame:)") 
    } 


    override init(frame: CGRect) { 
     self.stopwatch = StopwatchView(frame: CGRect(x: ScreenWidth/2 - 150, y: 0, width: 300, height: 100)) 
     self.stopwatch.setSecondsRemaining(0) 

     self.gamePoints = CounterLabelView(font: FontHUD!, frame: CGRect(x: ScreenWidth - 200, y: 30, width: 320, height: 70)) 
     gamePoints.textColor = UIColor.black 
     gamePoints.value = 0 

     super.init(frame: frame) 

     self.addSubview(gamePoints) 
     let pointsLabel = UILabel(frame: CGRect(x: ScreenWidth - 340, y: 30, width: 140, height: 70)) 
     pointsLabel.backgroundColor = UIColor.clear 
     pointsLabel.font = FontHUD 
     pointsLabel.text = " Points:" 
     self.addSubview(pointsLabel) 

     self.isUserInteractionEnabled = false 
     self.addSubview(self.stopwatch) 

     //load the button image 
     let hintButtonImage = UIImage(named: "btn")! 

     //the help button 
     self.hintButton = UIButton() 
     // hintButton.perform(#selector(HUDView.s)) 
     hintButton.setTitle("Hint!", for:.normal) 
     hintButton.titleLabel?.font = lHud 
     hintButton.setBackgroundImage(hintButtonImage, for: .normal) 
     hintButton.frame = CGRect(x: 50, y: 30, width: hintButtonImage.size.width, height: hintButtonImage.size.height) 

     // hintButton.center = self.center 
     //50, 30, hintButtonImage.size.width, hintButtonImage.size.height 
     hintButton.alpha = 1.0 
     hintButton.isUserInteractionEnabled = true 
     self.addSubview(hintButton) 

    // hintButton.addTarget(self, action: #selector(self.tapButton(_:)), for: .touchUpInside) 

     let g = UITapGestureRecognizer(target: self, action: #selector(self.h(_:))) 
     g.delegate = self 
     hintButton.addGestureRecognizer(g) 
    } 

    func h(_ sender: UITapGestureRecognizer) { 
     print("hey!") 
     fatalError() 
    } 

} 
+0

爲什麼你不直接使用addtarget而不是手勢 –

+0

它不工作aswell @ Anbu.Karthik – Aryan

+0

顯示你創建HUDView並將其放入界面的代碼。這是錯誤的代碼。 – matt

回答

1

的問題是一致self.isUserInteractionEnabled = false

您要添加按鈕的subviewHUDView。按鈕點按不起作用,因爲父視圖即:HUDView禁用了用戶交互,因此所有subViews的用戶交互都將被禁用。 進行更改爲self.isUserInteractionEnabled = true它將起作用。