如何在 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/