有必要将属性subrow: Int
添加到IndexPath
。为什么属性row: Int
和section: Int
会崩溃?
import UIKit
extension IndexPath {
init(subrow: Int, row: Int, section: Int) {
self.init(indexes: [section, row, subrow])
}
var subrow: Int {
get { return self[2] }
set { return self[2] = newValue }
}
}
let ip = IndexPath(subrow: 0, row: 1, section: 2)
print(ip.subrow == 0) // OK
print(ip.row == 1) // Crash!
print(ip.section == 2) // Crash!
答案 0 :(得分:1)
属性row
和section
在扩展程序中定义
在UIKit框架中IndexPath
。他们是"方便"
访问器,用于表视图或集合视图。
从API文档中可以看出它们只能用于索引路径 完全两个元素:
extension IndexPath {
/// Initialize for use with `UITableView` or `UICollectionView`.
public init(row: Int, section: Int)
/// The section of this index path, when used with `UITableView`.
///
/// - precondition: The index path must have exactly two elements.
public var section: Int
/// The row of this index path, when used with `UITableView`.
///
/// - precondition: The index path must have exactly two elements.
public var row: Int
}
另请参阅UIKit_FoundationExtensions.swift.gyb的源代码。
您可以改用下标方法:
let ip = IndexPath(subrow: 0, row: 1, section: 2)
print(ip[0]) // 2
print(ip[1]) // 1
print(ip[2]) // 0