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