Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 移除superview后未移除按钮_Ios_Swift_Uikit - Fatal编程技术网

Ios 移除superview后未移除按钮

Ios 移除superview后未移除按钮,ios,swift,uikit,Ios,Swift,Uikit,我在计时视图中有一个按钮,该按钮本身在计时器启动时显示剩余时间: func startTiming(button: UIButton, duration: Double, timingView: UIView?) { var duration = duration button.setTitle(String(Int(duration)), for: .normal) let timer = Timer.scheduledTimer(withTimeInterval:

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

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()
        }
    }
}
当用户在计时过程中点击按钮时,
timingView
将被删除:

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

    // remove timingView from superview
}
我希望
timingView
,每次取消计时器时,其所有子视图都会被删除,但是,如果我取消一个计时器,然后重新启动它,将有两个计时器同时运行(按钮标签在一秒钟内更改两次,更改为不同的数字),如何避免出现这种情况

编辑:


计时器
作为全局变量。在初始化之前,还要检查
定时器
是否为
nil
。在
timer.invalidate()之后写入
timer=nil
,我真的不喜欢强制展开superview。相反,你可以这样做

为您的
计时视图
指定一个标记,并确保它在superview中是唯一的。 e、 g

并确保
按钮
添加为
计时视图
的子视图(如果不是通过故事板完成)

将您的
cancelAbilityTiming()
修改为此

func cancelAbilityTiming(sender: UIButton) {
    for subview in self.view.subviews {
         if subview.tag == 99 {
             //Removing timingView
             subview.removeFromSuperview()
         }

    }
}

您确定已将按钮放置在计时视图中吗?@MidhunMP是的,我在interface Builder中执行了此操作检查按钮是否正确放置在计时视图中,如果可能,您可以共享ib树结构吗?@MidhunMP我添加了一张图片
func cancelAbilityTiming(sender: UIButton) {
    for subview in self.view.subviews {
         if subview.tag == 99 {
             //Removing timingView
             subview.removeFromSuperview()
         }

    }
}