ios - UIButton 未在 swift 中调用操作函数

标签 ios swift uibutton

我有一个以编程方式创建的按钮,但由于某种奇怪的原因,按下它时它不会激活该操作。有几个按钮,我已经从代码中删除了其他按钮,这是不起作用的按钮:

struct Buttons {

 var hintButton: UIButton!
 let hintBtn = UIButton(frame: CGRect(x: 10, y: 20, width: 70, height: 70))
 init() {hintBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    hintBtn.tag = 2
    hintBtn.setTitle("Hint", forState: .Normal)
    hintBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    hintButton = hintBtn
}

} 这是 viewController 中的代码:

  override func viewDidLoad() {
        super.viewDidLoad()

        AddAllGraphics()
        ButtonActions()
       self.buttons.hintBtn.enabled = true
    }

     func AddAllGraphics() {
    self.view.addSubview(buttons.hintBtn)
}

    func ButtonActions() {
      buttons.hintBtn.addTarget(self, action: "giveHint:", forControlEvents: .TouchUpInside)
    }

     func giveHint(sender:UIButton) {
        if(sender.tag == 2){
          buttons.hintBtn.enabled = false
          print("It Works")
        }
      }

我尝试在“giveHint”函数处放置一个断点,但按下按钮时它永远不会被调用。我尝试将 self.buttons.btn.userInteractionEnabled = true 放在 viewDidLoad 中,但它仍然不起作用。任何帮助将不胜感激!

最佳答案

上面的代码对我有用,但我必须正确初始化结构:

struct Buttons {
var hintButton: UIButton!
let hintBtn = UIButton(frame: CGRect(x: 10, y: 50, width: 70, height: 70))
init() {
    hintBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    hintBtn.tag = 2
    hintBtn.setTitle("Hint", forState: .Normal)
    hintBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    hintButton = hintBtn
}
}

关于ios - UIButton 未在 swift 中调用操作函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589022/

相关文章:

iOS leftSpacingConstraint 相对于屏幕高度

ios - RxSwift - 为什么将 ControlProperty 特性包装到驱动程序中?

ios - 大导航栏标题上方的字幕

swift - 在 swift 中转换和强制指针有什么区别?

ios - 将复选标记图像添加到多个按钮阵列

ios - 当我回到 Viewcontroller 时如何更改 View Controller 的 label.text?

objective-c - 获取从目录加载的 NSString 中的文件名

ios - 第一次点击后表格 View 单元格被取消选择。

swift - 将 magicCookie 从音频文件复制到音频队列失败

iphone - 如何获取 UIButton 中的点击次数?