【问题标题】:Get index of object from outlet collection从出口集合中获取对象的索引
【发布时间】:2014-08-22 08:53:41
【问题描述】:

在我的 UIViewController 我有插座集合:

@IBOutlet var cardButtons: Array<UIButton>

形成这个集合我想得到一个对象的索引,但是 Array 没有合适的方法。我发现 'indexOfObject' 方法只在 NSArray 中。

现在我将 cardButtons 属性转换为 NSArray

var cardButtonsArray = cardButtons as NSArray

这解决了我的问题,但也许还有另一种更干净的方法来做到这一点?

感谢您的帮助。

【问题讨论】:

标签: ios swift


【解决方案1】:

firstIndex 是一种您可以在 Swift 数组上使用的方法,它返回与您传入的对象匹配的第一个元素的索引: https://developer.apple.com/documentation/swift/array/2994720-firstindex

func getIndexOf(button: UIButton) -> Int? {
    let buttonIndex = cardButtons.firstIndex(of: button)
    return buttonIndex
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 2014-02-23
    • 2011-11-15
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多