Add a string property to a UIButton in Swift(将字符串属性添加到 Swift 中的 UIButton)
问题描述
如何在 Swift 中将字符串属性与 UIButton
关联?我不希望字符串显示为按钮文本,只是作为标识符或键分配给按钮.这是我到目前为止所拥有的:
How can I associate a string property with a UIButton
in Swift? I don't want the string to appear as the button text, simply to be assigned to the button as an identifier or a key. Here is what I have so far:
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)
}
所以我想我之后需要一些东西
So I think I need something after
// Set the identifier for each answer
self.identifier = self.currentQuestion!.answerIdentifier[index]
将标识符分配给按钮.
这样做的原因是我正在尝试实现决策树逻辑,以便我可以跟踪每个被点击的答案按钮以生成与最终结果相对应的代码字符串.
The reason for this is I'm trying to implement a decision tree logic so that I can keep track of each answer button that is tapped to generate a code string that will correspond to a final result.
推荐答案
如果你想识别的按钮应该有一个唯一的标识符(这个如果您曾经编写 UI 测试,这很重要).
You can use the accessibility identifier (button.accessibilityIdentifier
), if the button you want to identify should have a unique identifier (this matters if you're ever writing UI tests).
您还可以继承 UIButton 并添加一个变量 buttonIdentifier
.
You can also subclass UIButton and add a variable buttonIdentifier
.
class IdentifiedButton: UIButton {
var buttonIdentifier: String?
}
这篇关于将字符串属性添加到 Swift 中的 UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将字符串属性添加到 Swift 中的 UIButton


基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01