【发布时间】:2019-11-24 03:10:03
【问题描述】:
我的 swift 代码开始在 var myArray 中声明一个空的图像视图数组。在视图 didload 中,我尝试在数组的开头插入第一个 imageview。我的代码不起作用,myArray.insert(UIImageView, at: 0) 出现编译错误。
然后在myArray[0].frame = CGRect(x: view.center.x-0, y: view.center.y+100, width: 50, height: 50) 出现运行时错误,它指出超出索引范围。
import UIKit
class ViewController: UIViewController {
var myArray = [UIImageView]()
override func viewDidLoad() {
super.viewDidLoad()
myArray.insert(UIImageView, at: 0)
[myArray[0]].forEach({
$0.backgroundColor = UIColor.systemTeal
self.view.addSubview($0)
})
myArray[0].frame = CGRect(x: view.center.x-0, y: view.center.y+100, width: 50, height: 50)
}
}
【问题讨论】:
标签: arrays swift indexing insert imageview