【问题标题】:Place a empty array of image views on a view controller screen在视图控制器屏幕上放置一个空的图像视图数组
【发布时间】: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


    【解决方案1】:

    插入 UIImageView() 而不是 UIImageView。

    试试下面的代码:

    import UIKit
    
    class ViewController: UIViewController {
        var myArray = [UIImageView]()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            myArray.insert(UIImageView(), at: 0)
            myArray.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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多