ios - 将字符串属性添加到 Swift 中的 UIButton

标签 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 .

关于ios - 将字符串属性添加到 Swift 中的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30214519/

相关文章:

ios - 根据标签获取按钮标题 - Objective C

ios - 将 UIButton 添加为 UIWebView 的 subview 并在缩放时调整其大小

ios - 最小化 iOS 应用程序大小

ios - UITableView 在动画时剪辑到边界

ios - 同一 View 中两个 UITextField 的不同条件

ios - 在共享扩展中启用 Firebase 身份验证

ios - Frame.size.width 不返回正确的 UIButton 宽度

ios - 使用 SKPSMTPMessage 发送的电子邮件附件在 iOS 邮件客户端中显示为联系人

iOS Firebase 崩溃报告 - 运行构建脚本时出错

iOS:检测包含多个图像的 UIImageView 中的图像触摸