removeFromSuperview does not work well

Asked 2 years ago, Updated 2 years ago, 34 views

import UIKit

classViewController:UIViewController {
 varonVLine —onVerticalLine!
override func viewDidLoad(){
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from anib.
}

override funcdidReceiveMemoryWarning(){
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


override functouchesMoved(touches:Set<UITouch>, withEvent:UIEvent?) {
    onVLine = onVerticalLine (frame: CGRectZero)
    self.view.addSubview(onVLine)
    }

override functouchesEnded(touches:Set<UITouch>, withEvent:UIEvent?) {
    if(onVLine!=nil){
    self.onVLine.removeFromSuperview()
    }
    }

}



class onVerticalLine:UIView {
let_verticalLine: UIBezierPath=UIBezierPath()


override init (frame:CGRect) {
    super.init (frame:frame)
    print("online-initiated")
    _verticalLine.removeAllPoints()
    self.userInteractionEnabled=false;
    self.backgroundColor=UIColor (white:1, alpha:0)
    self.frame = CGRectMake(0,0, UISscreen.mainScreen().bound.width, UISscreen.mainScreen().bound.width)
    self.center= CGPointMake (UISscreen.mainScreen().bound.width/2, UISscreen.mainScreen().bound.height/2)
    print("vertical", self.frame)
    _verticalLine.lineWidth=1
    _verticalLine.moveToPoint(CGPointMake(frame.origin.x,0))
    _verticalLine.addLineToPoint(CGPointMake(frame.origin.x,self.frame.origin.y+frame.height))


}

required init?(coder adecoder:NSCoder) {
    super.init(coder:aDecoder)


}


override func drawRect (rect:CGRect) {

    print("onLinedrawRected")
    UIColor.blueColor().setStroke()
    _verticalLine.stroke()

    }
}

We have a program like the one above.
I want to remove the lines from ViewController, but the lines are still there.

By the way, in touchMoved,

self.view.addSubview(onVLines)
self.onVLines.removeFromSuperView()

Then it disappears well.

The execution itself seems to have been done, but it does not appear on the screen.
I tried self.view.setNeedsDisplay(), but it didn't respond either.
Thank you for your cooperation.

swift

2022-09-30 19:33

1 Answers

It says removeFromSuperView is not working, but I think it is working.
touchesMoved is called whenever the touch position changes or the touch strength changes.
Because you have created and repeatedly added onVerticalLine views that inherit the UIView, dozens of views are added to the parent view in no time.So what you see on the screen is the top of the dozens of views that look the same.

Typically, touchesBegan generates and adds views, repositions views generated by touchesMove, and
Often, the flow is to discard the view with touchesEnded and touchesCancelled and delete it from the parent view.


in touchesMoved If you write and debug print(__FUNCTION__), you may have noticed.


2022-09-30 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.