Reputation: 43
how can i select a subview and interact with it using swift and n subview. For now i have only 3 subviews and select 3 image with for. But for example how can I remove the subview with tag 2 after i create it?
func addSubView() {
for index in 1...3 {
let image: UIImage = UIImage(named: String(index))!
imageView = UIImageView(image: image)
imageView.tag = index
imageView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.removeSubview))
imageView.addGestureRecognizer(tapGesture)
imageView.frame = CGRect(x: randomNumber(range: 60...300), y: randomNumber(range: 60...400), width: 50, height: 50)
print(imageView)
self.backgroundImageView.addSubview(imageView)
}
}
func removeSubview() {
}
Upvotes: 0
Views: 420
Reputation: 131471
You could write a function removeSubviewWithTag(_:)
that would take a tag number as a parameter:
func removeSubviewWithTag(_ tag: Int) {
if let viewWithTag2 = backgroundImageView.viewWithTag(tag) {
viewWithTag2.removeFromSuperview()
}
}
And then call it as desired:
removeSubviewWithTag(2)
If you want to know if the function was able to find and remove a subview, you could make it return a discardable Bool result:
@discardableResult func removeSubviewWithTag(_ tag: Int) {
if let viewWithTag2 = backgroundImageView.viewWithTag(tag) {
viewWithTag2.removeFromSuperview()
return true
} else {
return false
}
}
And call it as follows:
if removeSubviewWithTag(2) {
print("Removed view")
} else {
print("unable to remove view")
}
Upvotes: 1
Reputation: 40211
Maybe add them to an array? Using tags is rarely the best solution.
var imageViews = [UIImageView]()
func addSubView() {
for index in 1...3 {
let image: UIImage = UIImage(named: String(index))!
imageView = UIImageView(image: image)
imageView.tag = index
imageView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.removeSubview))
imageView.addGestureRecognizer(tapGesture)
imageView.frame = CGRect(x: randomNumber(range: 60...300), y: randomNumber(range: 60...400), width: 50, height: 50)
print(imageView)
self.backgroundImageView.addSubview(imageView)
imageViews.append(imageView)
}
}
func removeSubview(at index: Int) {
imageViews[index].removeFromSuperview()
}
Upvotes: 0