简体   繁体   中英

Remove custom UIView(s) dynamically on user selection/highlighed in ios swift

I am new to swift, please kindly advise the best way to achieve this. Let say if there are 3 to 4 (custom) UIView(s) added under a parent view when user select/highlighted a particular one (eg the 2nd UIView), and this will get removed and the whole layout will re-render immediately. Any idea?

Connect all views to one IBOutletCollection, add gesture recognizer for tap and in recognizer callback just get the touch point and check if the point is contained in one of the views from the outlet collection.

@IBOutlet var views: [UIView]!

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGesture = UITapGestureRecognizer(target: self, action: Selector("viewTapped:"))
    self.view.addGestureRecognizer(tapGesture)
}

func viewTapped(tapGesture: UITapGestureRecognizer) {
    let locationInView = tapGesture.locationInView(view)

    for v in views {
        if CGRectContainsPoint(v.frame, locationInView) {
            v.removeFromSuperview()
        }
    }
}

Make sure you have your autolayout setup for the state in which each of the view is not there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM