arrays - 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
}
}
解决方案
您需要将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
然后从方法中删除等效的行。
推荐阅读
- windows - 在 Windows 命令终端中调出命令
- ansible - psutil 无法在 python3 virtualenv 中安装 pip:致命错误:Python.h:没有这样的文件或目录
- c - 使用 popen 与 telnet 交谈不会失败,但不会像预期的那样运行
- spring-boot - BeanCreationException:创建名为“springSecurityFilterChain”的 bean 时出错
- apache-spark - 是否有任何可以调整的 spark 配置参数以减少驱动程序节点的内存消耗?
- mysql - 带有 SUM 的 LEFT JOIN 不返回正确的值
- javascript - 使用回调功能的 Python 过滤方法
- web-services - 使用Mule Web服务Consumer连接器时弹出这个错误是什么意思,"The SOAP request timed out"
- rust - 如何比较 Arc
反对T? - apache - Apache Web 服务器已停止