ios - 删除其 super View 后按钮未删除

标签 ios swift uikit

我在timingView中有一个按钮,按钮本身显示计时器启动时剩余的时间:

func startTiming(button: UIButton, duration: Double, timingView: UIView?) {

    var duration = duration
    button.setTitle(String(Int(duration)), for: .normal)
    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in
        if duration > 0 {
            duration -= 1
            button.setTitle(String(Int(duration)), for: .normal)
        }
    }

    DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
        timer.invalidate()
        if timingView != nil {
            timingView?.removeFromSuperview()
        }
    }
}

每当用户在计时期间点击 button 时,timingView 就会被删除:

func cancelAbilityTiming(sender: UIButton) {
    sender.superview!.superview!.removeFromSuperview()

    // remove timingView from superview
}

我期待 timingView 并且每次取消计时器时它的所有 subview 都会被删除,但是,如果我取消计时器然后重新启动它,则会有 2 个计时器同时运行(按钮标签每秒更改两次,变为不同的数字),如何避免出现这种情况?

编辑:

enter image description here

最佳答案

timer作为全局变量。在初始化之前还要检查 timer 是否为 nil。在 timer.invalidate() 之后写入 timer = nil

关于ios - 删除其 super View 后按钮未删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41424519/

相关文章:

ios - 给定所需的宽度和字体,如何找到 UILabel 的高度?

iOS 13 状态栏样式无效(从未调用过 childForStatusBarStyle)

ios - 在 IBDesignableTextField 上的何处设置颜色

iphone - 检查 NSMutableArray 是否包含来自另一个数组的值

ios - 绘制完美的圆角线,Swift

ios - UIButton 没有更新?

ios - 在 UITableView 中禁用删除但启用移动单元格

iOS:自定义按钮(UIButton 的子类)- 无法更改边框属性

ios - 通过 iOS 共享的 UIActivityViewController 更改

ios - 导航(和状态)栏颜色与编程不同(alpha 自动设置为 0.85)