选择时删除子视图

时间:2017-07-13 13:23:35

标签: ios swift swift3

在这里,我通过点击superView:

为我的superView添加一个子视图
@IBAction func tapRecognizerAction(_ sender: UITapGestureRecognizer) {
    let location = sender.location(in: self.view)
    addNew(x: location.x, y: location.y)
}

func addNew(x : CGFloat, y : CGFloat){
    let testView: CustomView = CustomView(frame: CGRect(x: x, y: y, width: 50, height: 50)) 
    testView.backgroundColor = .blue
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(PlanViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){

}

触摸时如何删除特定的子视图。

2 个答案:

答案 0 :(得分:4)

您需要以这种方式传递点击视图

func addNew(x : CGFloat, y : CGFloat){
    let testView: CustomView = CustomView(frame: CGRect(x: x, y: y, width: 50, height: 50)) 
    testView.backgroundColor = .blue
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(PlanViewController.removeSubview(tapGestureRecognizer:))
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

然后在处理程序中检索点击的视图,然后将其从超级视图中删除

func removeSubview(tapGestureRecognizer: UITapGestureRecognizer){
    let tappedView = tapGestureRecognizer.view as! CustomView
    tappedView.removeFromSuperview()

}

答案 1 :(得分:-1)

如何在函数外部保持对视图的引用?

let testView: CustomView = CustomView(frame: CGRect(x: x, y: y, width: 50, height: 50)) 
func addNew(x : CGFloat, y : CGFloat){

    testView.backgroundColor = .blue
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(PlanViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}
func removeSubview(){
    testView.removeFromSuperview()
}