在下面的代码中:
let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as MyTableViewCell // 'UITableViewCell' is not convertible to 'MyTableViewCell'; did you mean to use 'as!' to force downcast?
我们有错误提示 UITableViewCell
不能转换为 MyTableViewCell
。
因此编译器建议进行强制转换:
let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as! MyTableViewCell // ?!?!?!
但是,这感觉很难看。
在处理 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
时,是否没有强制转换的替代方法?这真的是在 Swift 中实现这一目标的最惯用的方法吗?
谢谢!
最佳答案
Is this really the most idiomatic way
当然。这是完全标准的。
您可以像这样安全地垂头丧气:
if let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as? MyTableViewCell {
但在这种情况下,我认为不值得这样做,因为如果结果证明这不是 MyTableViewCell,那么您确实希望崩溃。 p>
关于ios - 在 Swift 中编写自定义 UITableViewCell 时强制向下转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169147/