I want to add a new subview every time I swipe right, but then it will stack many times if I do not destroy the previous subview. I know how to remove it, but I am struggling with the logic of how to remove it only after I add a new one.
I have tried this:
var view1: UIView?
var view2: UIView?
var ctrl = false
override func viewDidLoad() {
super.viewDidLoad()
view1?.addSubview(CustomView(frame: self.view.bounds))
}
func addView(){
if let test1 = view1, let test2 = view2 {
if ctrl == true {
test1.addSubview(CustomView(frame: self.view.bounds))
test2.removeFromSuperview()
ctrl = false
}else{
test2.addSubview(CustomView(frame: self.view.bounds))
test1.removeFromSuperview()
ctrl = true
}
}
}
@IBAction func swipeRight(_ sender: Any) {
print("Right")
UIView.animate(withDuration: 1, animations: {
self.view.layer.backgroundColor = .black
}){(isFinished) in
self.addView()
//I am hoping that after this the view stack before will be removed
}
}
the Class CustomView is this:
var primaryColors: [UIColor] = [
.red,
.yellow,
.blue]
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
primaryColors.shuffle()
let leftRect = CGRect(x: 0, y: 0, width: rect.size.width/2, height: rect.size.height)
primaryColors[0].set()
guard let leftContext = UIGraphicsGetCurrentContext() else { return }
leftContext.fill(leftRect)
let rightRect = CGRect(x: rect.size.width/2, y: 0, width: rect.size.width/2, height: rect.size.height)
primaryColors[1].set()
guard let rightContext = UIGraphicsGetCurrentContext() else { return }
rightContext.fill(rightRect)
}
}