ios - 内部修饰 (@IBAction) 不适用于 UIButton 子类

标签 ios swift uibutton

我创建了 UIButton 的子类:

import UIKit

@IBDesignable
class CheckboxButton: UIButton {

@IBInspectable var checkboxBackgroundColor: UIColor = Project.Color.baseGray
@IBInspectable var textColor: UIColor = Project.Color.mainDarkText

@IBInspectable var checkboxHighlightedBackgroundColor: UIColor = Project.Color.main
@IBInspectable var highlightedTextColor: UIColor = Project.Color.mainBrightText

// MARK: - Properties
var isChecked: Bool = false {
    didSet {
        changeState()
    }
}


// MARK: - Overrides
override init(frame: CGRect) {
    super.init(frame: frame)
    setupView()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupView()
}

override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {

    if isChecked {
        isChecked = false
    } else {
        isChecked = true
    }

    return false
}

override func prepareForInterfaceBuilder() {
    changeState()
}


// MARK: - @IBActions



// MARK: - Functions
private func setupView() {
    isUserInteractionEnabled = true
    changeState()
}

private func changeState() {
    if isChecked {
        backgroundColor = checkboxHighlightedBackgroundColor
        self.setTitleColor(highlightedTextColor, for: .normal)
    } else {
        backgroundColor = checkboxBackgroundColor
        self.setTitleColor(textColor, for: .normal)
    }
}
 }

现在我在 Storyboard 中添加了一个按钮,并赋予它 CheckboxButton 类。一切正常。然后我添加了一个 IBAction,如下所示:

@IBAction func pointBtnTapped(_ sender: CheckboxButton) {
    print("tapped")
    selectButton(withNumber: sender.tag)
}

但这不起作用(没有打印出来)。它适用于普通按钮,但如果按钮是 CheckboxButton 的子类,则无效。你有什么想法吗?

编辑:截图 https://www.dropbox.com/s/ewicc349ag9l6y2/Screenshot%202016-10-06%2023.41.39.png?dl=0

https://www.dropbox.com/s/vxevzscueproivc/Screenshot%202016-10-06%2023.42.33.png?dl=0 (无法将它们嵌入此处。不知道为什么)

谢谢!

最佳答案

您通过覆盖 beginTracking() 并始终返回 false 破坏了 UIButton。这会对按钮进行洗脑,使其认为它永远不会被点击。

你的意图是什么?在任何情况下,在那里返回 true,您的代码将触发 @IBAction

编辑:您通过使用用于高度自定义行为(例如非矩形按钮)的低级方法来考虑问题。你只需要:

How to use UIButton as Toggle Button?

关于ios - 内部修饰 (@IBAction) 不适用于 UIButton 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39905830/

相关文章:

ios - 使用 Appcelerator 在 iOS 上退出应用程序时音频不在后台播放

ios - Xcode : Multiple Audio Files, 单按钮

Swift:- 在自定义 tableview 单元格中单击按钮时将标签值增加 1

ios - 在 swift 中使用新的 Podfile 时如何忽略警告?

ios - Xcode Swift 删除 MKPolyline

ios - Xcode 按钮图像不显示

iphone - 如何打开 iPhone 的默认浏览器?

ios - 将 AIR 应用程序移植到 iOS : do I need an iPad to debug the app?

ios - Flutter iOS 应用程序在启动时显示白屏并在该屏幕上挂断

ios - 滚动并按搜索栏上的取消时应用程序崩溃