UIView甚至在从superview中删除后重新出现

时间:2017-06-21 18:02:47

标签: ios swift uiview swift3

我有一个问题,如果我从超级视图中删除子视图,然后当我推送到另一个VC并返回所有删除的子视图重新出现在视图中我已经尝试了所有内容并检查了我的代码,如果viewDidApper也是。

enter image description here

//HERE IS HOW I ADD VIEWS

func addusers() {

    for user in 0...5 {
        let radarButton = PRButton(frame: CGRect(x: 0, y: 0, width: itemSize.width, height: itemSize.height+14))
        radarButton.profileButton?.setImage(UIImage(named: "dummy-avatar.png"), for: UIControlState())
        radarButton.profileName.setTitle("test \(user)", for: .normal)

        repeat {
            let center = generateCenterPointInRadar()
            radarButton.center = CGPoint(x: center.x, y: center.y)

        } while (itemFrameIntersectsInOtherItem(radarButton.frame))
        radarButton.profileButton?.addTarget(self, action: #selector(didTapUser), for: .touchUpInside)
        radarButton.profileName?.addTarget(self, action: #selector(didTapUser), for: .touchUpInside)
        self.addSubview(radarButton)
        items.append(radarButton)
    }

}

//HERE IS HOW I REMOVE VIEWS
func removeAllUsers() {
    for view in self.subviews {
        if view is PRButton  {
            view.removeFromSuperview()
        }
    }
    items.removeAll()

}
//Remove from superview
    override func removeFromSuperview() {

        UIView.beginAnimations("", context: nil)
        UIView.setAnimationDuration(1)
        self.alpha = 0
        UIView.setAnimationDidStop(Selector(("callSuperRemoveFromSuperview")))
        UIView.commitAnimations()

    }

fileprivate func callSuperRemoveFromSuperview() {
    super.removeFromSuperview()
}

提前致谢

2 个答案:

答案 0 :(得分:2)

我查看了测试项目。 我想我发现了问题,它出现在override func removeFromSuperview() 我将其注释掉并编辑removeAllUsers()

func removeAllUsers() {
    for view in self.subviews {
        if view is PRButton  {
          UIView.animate(withDuration: 1, animations: { 
            view.alpha = 0
          }, completion: { (finished) in
            view.removeFromSuperview()
          })
        }
    }
    items.removeAll()

}

现在,当我回到viewController

时,我看不到任何重复的用户

答案 1 :(得分:1)

首先要看......

PRButton中覆盖removeFromSuperview() - 但您的结构不正确,而且您实际上从未删除该视图。

替换为:

override func removeFromSuperview() {

    UIView.animate(withDuration: 1.0, animations: ({
        self.alpha = 0.0
    }), completion: { _ in
        self.callSuperRemoveFromSuperview()
    })

}

您也可以简单地拨打super.removeFromSuperview()而不是其他self.callSuperRemoveFromSuperview()功能。

了解Debug View Hierarchy功能......您会立即看到它。