【问题标题】:Fill programmatically UISegmentedControl using swift使用 swift 以编程方式填充 UISegmentedControl
【发布时间】:2017-02-04 10:40:08
【问题描述】:

是否可以使用 swift 以编程方式填充 UISegmentedControl 的值?

【问题讨论】:

    标签: ios swift swift3 uisegmentedcontrol


    【解决方案1】:
    let segmentedControl = UISegmentedControl()
    segmentedControl.insertSegment(withTitle: "Title", at: 0, animated: true)
    segmentedControl.setTitle("Another Title", forSegmentAt: 0)
    

    【讨论】:

      【解决方案2】:

      如果我没记错的话,您的意思是您想以编程方式将段添加到“UISegmentedControl”组件,而不使用 Interface Builder。

      是的,有可能:

      // Assuming that it is an "IBOutlet", you can do this in your "ViewController":
      class ViewController: UIViewController {
      
          @IBOutlet weak var segmentedControl: UISegmentedControl!
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              // remove all current segments to make sure it is empty:
              segmentedControl.removeAllSegments()
      
              // adding your segments, using the "for" loop is just for demonstration:
              for index in 0...3 {
                 segmentedControl.insertSegmentWithTitle("Segment \(index + 1)", atIndex: index, animated: false)
              }
      
              // you can also remove a segment like this:
              // this removes the second segment "Segment 2"
              segmentedControl.removeSegmentAtIndex(1, animated: false)
          }
      
          // and this is how you can access the changing of its value (make sure that event is "Value Changed")
          @IBAction func segmentControlValueChanged(sender: UISegmentedControl) {
              print("index of selected segment is: \(sender.selectedSegmentIndex)")
          }
      }
      

      【讨论】:

        【解决方案3】:

        我解决了我的问题,使用@RyuX51 的解决方案 我现在的代码是:

        class MyCustomViewController: UIViewController{
        
            @IBOutlet weak var ServicesSC: UISegmentedControl!
        
            override func viewDidLoad() {
                super.viewDidLoad()
        
                ServicesSC.removeAllSegments()
        
        
                ServicesSC.insertSegment(withTitle: "Title", at: 0, animated: true)
                ServicesSC.setTitle("Another Title", forSegmentAt: 0)
        
            }
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 2015-12-13
          • 2017-05-23
          • 1970-01-01
          • 2012-02-23
          • 2021-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-06
          相关资源
          最近更新 更多