Ng Hsiao Qin Ng Hsiao Qin -4 years ago 81
iOS Question

Remove Subview not working

I have add a subview into an UIImageView and i try to remove the subview by calling the removeFromSuperview function but it is not working and the subview is still there...Any idea?

Below is my code:

var path = CGMutablePath()
path.move(to: CGPoint(x: 127.5, y: 13.5))
path.addLine(to: CGPoint(x: 165.0, y: 13.5))
path.addLine(to: CGPoint(x: 165.0, y: 51.5))
path.addLine(to: CGPoint(x: 127.5, y: 51.5))
path.closeSubpath()

var shape = CAShapeLayer()
shape.path = path
shape.opacity = 0.5
shape.lineWidth = 3.0
shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).cgColor

let pathClick = path.contains(location)

if pathClick == true
{
let avgX = (127.5 + 127.5 + 165 + 165) / 4
let avgY = (13.5 + 13.5 + 51.5 + 51.5) / 4
let centerLocation = CGPoint(x: avgX, y: avgY)

bubble.frame = CGRect(x: 0, y: 0, width: 15, height: 15)
bubble.center = centerLocation
mapImageView.layer.addSublayer(shape)
mapImageView.addSubview(bubble)
handleMore()
}
else
{
bubble.removeFromSuperview()
print("working")
}

Answer Source

it is not removing, because that is not view - you have added before. That is a another instance. You may access previous one from mapImageView.subviews, that is array of all subviews of your mapImageView. Identify which one is yours to remove, and use identifiedView.removeFromSuperview. You may use tags to identify your subviews. Another way is to remember your view when you are adding it as subview, and remove that view from superView. Anyway, you need to identify right subview.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download