2017-07-13 34 views
0

在這裏,我添加一個子視圖到我的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(){ 

} 

如何刪除特定的子視圖,當我觸摸它。

回答

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

你怎麼樣堅持參考函數外的視圖?

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() 
}