ios - 无法为索引为'UIButton'的[uiButton]类型下标(Swift)

标签 ios swift uibutton

我有一个UIButton radioController.buttonsArray = [ button1, button2, button3 ]数组,想通过将所选按钮传递给函数radioController.defaultButton = radioController.buttonsArray[selectedButton]来将默认设置为所选按钮
我想使用一个字符串(最初是一个整数,但是数组中的位置随设计而不断变化),因此在此之上,我尝试了:

var selectedButton: UIButton = button1
switch currentSelection {
    case "selection 1" : selectedButton = button1
    case "selection 2" : selectedButton = button2
    case "selection 3" : selectedButton = button3
    default: 
        break
} 
我首先收到错误消息:可选类型'[UIButton]?的值?必须解开以引用包装的基本类型'[UIButton]'的成员'下标'
但是在“修复”它之后((使用?或!),我得到消息:
无法为类型为[uiButton]的值下标为'UIButton'类型的索引
我如何声明selectedButton来做到这一点?或者,还有更好的方法?

最佳答案

您只能使用Int下标数组。如果要查找数组中特定元素的索引,则应在数组上使用firstIndex(of:)函数。
但是,对于您的特定需求,似乎根本没有理由访问数组,因为您已经可以访问所需的元素。
您可以只做radioController.defaultButton = selectedButton

关于ios - 无法为索引为'UIButton'的[uiButton]类型下标(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63119671/

相关文章:

ios - 如何检测 UIButton 的触摸结束事件?

iOS : dealloc & IBOutlet

ios - 链接器错误 - Objective-C

swift - 我如何在 Swift/Alamofire 中使用 multipartFormData?

ios - 如何使用 SDWebImage 将 alpha 属性添加到 UIImage 集?

swift - subview 中无响应的 UIButton 添加到 UIStackView

iPhone UIButton 的作用类似于 UISwitch

ios - 降级部署目标后为"failed to emit precompiled header"

ios - 需要在 UILabel 的文本中获取多个@符号的 NSRanges 及其后面的文本

ios - iOS 摄像头输入的实时主色检测