首页 > 解决方案 > use @objc func to place a empty array of imageViews

问题描述

I want to use my swift code to place a imageview everytime the func moveRight is called. I want each new imageView to be separated by a 50 on the y axis. Right now my code compiles but nothing is changing when the function is called. But in the debug area I am seeing the count increasing.

import UIKit

class ViewController: UIViewController {
   var myArray = [UIImageView]()
   var bt = UIButton()
   var count : Int = 0

   override func viewDidLoad() {
      super.viewDidLoad()
      self.view.addSubview(bt)
      bt.backgroundColor = UIColor.systemOrange
      bt.frame = CGRect(x: view.center.x - 0, y: view.center.y , width: 50, height: 50)
      bt.addTarget(self, action: #selector(moveRight), for: .touchUpInside)
   }

   @objc func moveRight() {
      print("Yes")

      myArray.forEach({
         $0.backgroundColor = UIColor.systemTeal
         self.view.addSubview($0)
      })
      var ht = 50

      myArray.insert(UIImageView(), at: count)

      print("Your Count is ", count)

      myArray[count].frame = CGRect(x: view.center.x - 0, y: view.center.y + CGFloat(ht), width: 50, height: 50)

      count += 1
      ht += 50  
    }
}

标签: arraysswiftfor-loopinsertint

解决方案


您需要将ht变量移到moveRight()方法之外。

当前,每次运行该方法时,您都会重新创建变量并将其初始值设置为 50,然后使用它来设置您的位置。

你需要做

class ViewController: UIViewController {
   var myArray = [UIImageView]()
   var bt = UIButton()
   var count : Int = 0
   var ht = 50        //initialise it here, then update it in the moveRight() method
   //etc

然后从方法中删除等效的行。


推荐阅读