Swift 边界不可用

Swift Bounds unavailable

当我构建应用程序时,错误指向下面的代码并显示 'bounds' 不可用。该代码以前有效,但现在导致构建失败。

let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.collectionView)

let cellIndexPath = self.collectionView?.indexPathForItemAtPoint(pointInTable)
println(cellIndexPath)

sender可能是一个UIButton,但是Swift不知道那个。它只知道你告诉它什么。你必须告诉它,让Swift知道这是一个有bounds属性的东西。最简单的方法是投:

let button = sender as UIButton
let pointInTable: CGPoint = button.convertPoint(button.bounds.origin, toView: self.collectionView)

此外,您确定 self.collectionView 不是可选项吗?在 Xcode/Swift 的某些版本中,它是,您必须将其解包 (self.collectionView!)。