在Swift中添加一个string属性到UIButton

我怎样才能将一个string属性与一个UIButton在Swift中关联? 我不希望string显示为button文本,只是将其作为标识符或键分配给button。 这是我到目前为止:

 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] 

将标识符分配给button。

原因是我试图实现一个决策树的逻辑,以便我可以跟踪每个答案button被点击生成一个代码string,将对应于最终的结果。

使用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运行时的更多信息,我build议您查看这篇NSHipster文章 。

你可以buttonIdentifier UIButton并添加一个variablesbuttonIdentifier

 class IdentifiedButton: UIButton { var buttonIdentifier: String? } 

你可以使用UIButton的accessibilityIdentifier属性。

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

使用

 button.accessibilityIdentifier = "some text" 

是标签的。

您可以使用与button相关联的string创build一个数组。 然后将button标签设置为您想要与button关联的string的索引。 因此:

 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] }