UISegmentedControl以编程方式更改段数

时间:2012-07-24 20:33:53

标签: xcode ios5 uisegmentedcontrol

我在名为SegmentedAnswer的视图中有一个UISegmentedControl,有四个段。 有没有办法以编程方式更改段数? 非常感谢!

7 个答案:

答案 0 :(得分:120)

是的,您可以使用

removeSegmentAtIndex:(NSUInteger) animated:(BOOL)

insertSegmentWithTitle:(NSString *) atIndex:(NSUInteger) animated:(BOOL)

答案 1 :(得分:42)

要完全替换细分,您可以使用以下功能:

- (void)setSegments:(NSArray *)segments
{
    [segmentController removeAllSegments];

    for (NSString *segment in segments) {
        [segmentController insertSegmentWithTitle:segment atIndex:segmentController.numberOfSegments animated:NO];
    }
}

希望这会有所帮助。

答案 2 :(得分:17)

这里有一个小的Swift扩展来用新值数组替换当前的segmentedControl

Swift 3

extension UISegmentedControl {
    func replaceSegments(segments: Array<String>) {
        self.removeAllSegments()
        for segment in segments {
            self.insertSegmentWithTitle(segment, atIndex: self.numberOfSegments, animated: false)
        }
    }
}

Swift 4

extension UISegmentedControl {
    func replaceSegments(segments: Array<String>) {
        self.removeAllSegments()
        for segment in segments {
            self.insertSegment(withTitle: segment, at: self.numberOfSegments, animated: false)
        }
    }
}

答案 3 :(得分:3)

这是一个用一系列字符串替换段的Swift扩展。它类似于此处给出的another answer,除了它可以与任何序列一起使用,这意味着你也可以传入切片,集合等。

extension UISegmentedControl {

    /// Replace the current segments with new ones using a given sequence of string.
    /// - parameter withTitles:     The titles for the new segments.
    public func replaceSegments<T: Sequence>(withTitles: T) where T.Iterator.Element == String {
        removeAllSegments()
        for title in withTitles {
            insertSegment(withTitle: title, at: numberOfSegments, animated: false)
        }
    }
}

答案 4 :(得分:2)

为了完整起见(因为我最终在这里寻找如何在xib中实现相同的东西),这里是如何在xib中实现的:

enter image description here

答案 5 :(得分:0)

为我工作,UIsegmentedControll包含两个段,我想在索引2中添加一个,在swift 2.2中使用此代码使用:

SEG_TipoFiltro.insertSegmentWithTitle("Title", atIndex: 2, animated: false)

答案 6 :(得分:0)

使用代码在swift4中添加和删除细分

class ViewController: UIViewController {

  @IBOutlet weak var segment1: UISegmentedControl!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }

  @IBAction func insert(_ sender: Any) {  
    segment1.insertSegment(withTitle: "\(segment1.numberOfSegments+1)", at: segment1.numberOfSegments, animated: true)  
  }

  @IBAction func remove(_ sender: Any) {  
    segment1.removeSegment(at: segment1.numberOfSegments-1, animated: true)
  }
}