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

时间:2015-05-13 12:17:18

标签: 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]

将标识符分配给按钮。

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

5 个答案:

答案 0 :(得分:10)

您可以继承UIButton并添加变量buttonIdentifier

class IdentifiedButton: UIButton {
    var buttonIdentifier: String?
}

答案 1 :(得分:10)

使用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

答案 2 :(得分:8)

您可以使用UIButton的 accessibilityIdentifier 属性。

@IBOutlet weak var button: UIButton!
button.accessibilityIdentifier = "Some useful text"

答案 3 :(得分:3)

使用

button.accessibilityIdentifier = "some text"

不是标签。

答案 4 :(得分:1)

您可以使用要与按钮关联的字符串创建一个数组。然后将按钮标记设置为要与按钮关联的字符串的索引。因此:

var myStrings = ["First","Second","Third"]

button.tag = //insert a number corresponding to the string index in myStrings that you want for the button

func buttonPressed(sender: UIButton){
    var selectedString = myString[sender.tag]
}