【问题标题】:UISegmentedControl deselect / reset after view disappears视图消失后 UISegmentedControl 取消选择/重置
【发布时间】:2018-12-27 23:37:19
【问题描述】:

我正在尝试修复一个小错误。我有一个UISegmentedControl,如果我在按下段时向后导航(不松开从屏幕上选择段的手指),它会一直显示用户交互:

我试图取消选择viewWillDisappear 上的段,但我没有任何区别。关于如何重置UISegmentedControl 状态的任何想法?

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    fixedPositionSegmentControl.selectedSegmentIndex = UISegmentedControl.noSegment
    fixedPositionSegmentControl.selectedSegmentIndex = 0
}

【问题讨论】:

  • 显示你尝试过的代码
  • 用我的viewWillDisappear函数编辑
  • 删除fixedPositionSegmentControl.selectedSegmentIndex = 0
  • 我希望选择回退到第一段 (0)。

标签: ios swift uisegmentedcontrol


【解决方案1】:

问题在于,在这种特定情况下(在触摸控件时离开屏幕)分段控件的 touchesEnded / touchesCancelled 函数不会被调用。所以你可以通过编程方式取消触摸:

override func viewDidDisappear(_ animated: Bool) {
    segmentedControl.touchesCancelled(Set<UITouch>(), with: nil)
    super.viewDidDisappear(animated)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    segmentedControl.selectedSegmentIndex = 0
}

子类化UISegmentedControl 甚至可能是更简洁(但可能过大)的方法:

class SegmentedControl: UISegmentedControl {

    // property to store the latest touches
    private var touches: Set<UITouch>?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.touches = touches
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        self.touches = touches
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        self.touches = nil
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        self.touches = nil
    }

    override func didMoveToWindow() {
        // cancel pending touches when the view is removed from the window
        if window == nil, let touches = touches {
            touchesCancelled(touches, with: nil)
        }
    }

}

使用这种方法,您可以简单地重置viewWillAppear 中的索引:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    segmentedControl.selectedSegmentIndex = 0
}

【讨论】:

  • 很棒的方法。 segmentedControl.touchesCancelled(Set&lt;UITouch&gt;(), with: nil) 正是我想要的。也为您的SegmentedControl 点赞!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
相关资源
最近更新 更多