单击表行时更改UISlider控制器

时间:2017-12-28 01:56:01

标签: ios swift uitableview uislider

我想在用户选择tableview行时创建一个UISlider。它更新了min& max value将滑块移动到由变量设置的值。

滑块位于不同的Viewcontroller中,然后是tableview。我使用结构将值传递给滑块(在下面发布)。此时,我可以在视图控制器viewDidLoad中设置struct值时使滑块工作。但是,当选择了tableview行时,我无法更改UIslider。我认为问题是当选择行时,UIslider的视图不会刷新。使用容器视图,使用滑块将Tableview嵌入到视图中。

     struct GlobalSliderValues {

        static var minimumValue = Int()
        static var maximumValue = Int()
        static var lowerValue = Int()
        static var UpperValue = Int()
        static var locationValue = Int()
        static var sliderValue = Int()
        static var setValue = Int()
    }

// Slider ViewController 

override func viewDidLoad() {
    super.viewDidLoad()

    sliderOutlet.minimumValue = Float(GlobalSliderValues.minimumValue)
    sliderOutlet.maximumValue = Float(GlobalSliderValues.maximumValue)
    sliderOutlet.isContinuous = true
    sliderOutlet.tintColor = UIColor.green
    sliderOutlet.value = Float(GlobalSliderValues.sliderValue)

}


// Method attempting to change Slider

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    switch indexPath.row {
    case 3:
        GlobalSliderValues.minimumValue = 100
        GlobalSliderValues.maximumValue = 10000000
        GlobalSliderValues.sliderValue = 100000000

    default:
        break
    }
}

1 个答案:

答案 0 :(得分:0)

尝试重构滑块分配,同时添加NotificationCenter以便能够从任何地方刷新滑块,这样做:

override func viewDidLoad() {
  super.viewDidLoad()

  sliderOutlet.isContinuous = true
  sliderOutlet.tintColor = UIColor.green
  self.refreshSlider()
}

@objc func refreshSlider() {
  sliderOutlet.minimumValue = Float(GlobalSliderValues.minimumValue)
  sliderOutlet.maximumValue = Float(GlobalSliderValues.maximumValue)
  sliderOutlet.value = Float(GlobalSliderValues.sliderValue)
}

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  NotificationCenter.default.addObserver(self, selector: #selector(self.refreshSlider), name: Notification.Name("refreshSlider"), object: nil)
}

override func viewDidDisappear(_ animated: Bool) {
  super.viewDidDisappear(animated)
  NotificationCenter.default.removeObserver(self, name: Notification.Name("refreshSlider"), object: nil)
}

最后在didSelectRowAt内你将拥有:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  switch indexPath.row {
  case 3:
    GlobalSliderValues.minimumValue = 100
    GlobalSliderValues.maximumValue = 10000000
    GlobalSliderValues.sliderValue = 100000000
    NotificationCenter.default.post(name:Notification.Name("refreshSlider"), object: nil)
  break:
  default:
    break
  }
}