ios – 在Swift中向UIButton添加字符串属性

如何在 Swift中将字符串属性与UIButton相关联?我不希望字符串显示为按钮文本,只是将其指定为按钮作为标识符或键.这是我到目前为止:
func createAnswerButtons() {

    var index:Int
    for index = 0; index < self.currentQuestion?.answers.count; index++ {

        // Create an answer button view
        var answer:AnswerButtonView = AnswerButtonView()
        selection.setTranslatesAutoresizingMaskIntoConstraints(false)

        // Place into content view
        self.scrollViewContentView.addSubview(answer)

        // Add a tapped gesture recognizer to the button
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self,action: Selector("answerTapped:"))
        answer.addGestureRecognizer(tapGesture)

        // Add constraints etc

        // Set the answer button text
        let answerText = self.currentQuestion!.answers[index]
        answer.setAnswerText(answerText)

        // Set the identifier for each answer button
        self.identifier = self.currentQuestion!.answerIdentifier[index]

        // Add to the selection button array
        self.answerButtonArray.append(answer)
}

所以我想我需要一些东西

// Set the identifier for each answer
        self.identifier = self.currentQuestion!.answerIdentifier[index]

将标识符分配给按钮.

这样做的原因是我正在尝试实现一个决策树逻辑,这样我就可以跟踪每个被点击的答案按钮,以生成一个与最终结果相对应的代码字符串.

解决方法

使用Objective-C运行时,我们可以在运行时向类添加属性
extension UIButton {
    private struct AssociatedKeys {
        static var DescriptiveName = "nsh_DescriptiveName"
    }

    @IBInspectable var descriptiveName: String? {
        get {
            return objc_getAssociatedobject(self,&AssociatedKeys.DescriptiveName) as? String
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedobject(
                    self,&AssociatedKeys.DescriptiveName,newValue as Nsstring?,UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                )
            }
        }
    }
}

添加@IBInspectable还允许我们通过Interface Builder设置descriptiveName属性.

有关Objective-C运行时的更多信息,我建议您查看this NSHipster article.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...