我嘗試為螢屏上的每次點擊添加 UIView,但是一旦我點擊 UIView 添加,但我無法在螢屏上保護他,當我未點擊時他就消失了。我應該怎么做才能在螢屏上安全 UIView 并點擊一次以添加第二個 UIView 和我保存的每個 UIView?
import UIKit
class ViewController: UIViewController {
// MARK: - Property
let circle: UIView = {
let circle = UIView()
circle.frame.size.height = 100
circle.frame.size.width = 100
circle.layer.borderWidth = 10
circle.layer.borderColor = UIColor.white.cgColor
circle.layer.cornerRadius = 50
return circle
}()
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
addRecognizer()
view.backgroundColor = .red
}
// MARK: - Methods
@IBAction func tappedRecognizer(_ recognizer: UITapGestureRecognizer) {
let tapLocation = recognizer.location(in: view)
let circleHeight = circle.frame.size.height
let circleWidth = circle.frame.size.width
print(tapLocation)
circle.frame.origin = .init(x: tapLocation.x - circleWidth/2, y: tapLocation.y - circleHeight/2)
view.addSubview(circle)
}
func addRecognizer() {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(tappedRecognizer(_:)))
self.view.addGestureRecognizer(recognizer)
}
}
uj5u.com熱心網友回復:
在您的類和方法中添加陣列以創建新圓:
class ViewController: UIViewController {
// MARK: - Property
var circles = [UIView]()
func newCircle(atLocation tapLocation: CGPoint) -> UIView {
let circle = UIView()
circle.frame.size.height = 100
circle.frame.size.width = 100
circle.layer.borderWidth = 10
circle.layer.borderColor = UIColor.white.cgColor
circle.layer.cornerRadius = 50
circle.frame.origin = .init(x: tapLocation.x - circle.frame.size.width/2,
y: tapLocation.y - circle.frame.size.height/2)
circles.append(circle)
return circle
}
@IBAction func tappedRecognizer(_ recognizer: UITapGestureRecognizer) {
let tapLocation = recognizer.location(in: view)
print(tapLocation)
let circle = newCircle(atLocation: tapLocation)
view.addSubview(circle)
}
}
另一種方法是使用計算屬性(這可能是您試圖實作的)。為此,只需從屬性定義中洗掉 = :
let circle: UIView { /: no =
get {
let circle = UIView()
circle.frame.size.height = 100
circle.frame.size.width = 100
circle.layer.borderWidth = 10
circle.layer.borderColor = UIColor.white.cgColor
circle.layer.cornerRadius = 50
return circle
}
} // no ()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368540.html
