【问题标题】:Cannot subscript a value of type '[UIImage]' with an index of type 'CGFloat' [duplicate]无法使用“CGFloat”类型的索引为“[UIImage]”类型的值下标 [重复]
【发布时间】:2019-02-13 00:58:09
【问题描述】:

我有这个错误。

无法使用“CGFloat”类型的索引为“[UIImage]”类型的值下标

为什么会这样?

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if(scrollView.contentOffset.y > self.view.frame.height) {
        //(1/10) because we are changing the scrollView every 1/10 of the screen
        let pictureCount = scrollView.contentOffset.y/scrollView.frame.height*(1/10)
        imageView.image = images[pictureCount]
    }

}

【问题讨论】:

  • imageView.image = images[Int(pictureCount)] 将 CGFloat 转换为 Int 以访问具有索引的数组。

标签: swift xcode


【解决方案1】:

不能在 Swift 中使用 CGFloat 来索引数组,你可以通过简单的转换为 Int 来修复它。

let priceCount : CGFloat = 3 /* just for testing purposes */
let images = [UIImage]()
let imageView = UIImageView()

imageView.image = images[Int(priceCount)]

@prekshya basnet 在 cmets 中指出了这个演员表。


数组只有Int的位置,如:

array[0]array[1]array[2]

如果 CGFloats 可以索引数组,那会产生歧义,因为像 array[0.5] 这样的东西可能是一个访问选项

注意:CGFloatInt 的转换只会删除十进制值而不对其进行四舍五入,这意味着您是否有Int(CGFloat(0.1))Int(CGFloat(0.9)) 都没有关系,这将始终导致0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2017-03-19
    • 2020-02-08
    • 2016-11-04
    • 1970-01-01
    相关资源
    最近更新 更多