80

有没有办法以编程方式更改段数?

4

7 回答 7

139

是的,您可以使用

removeSegmentAtIndex:(NSUInteger) animated:(BOOL)

insertSegmentWithTitle:(NSString *) atIndex:(NSUInteger) animated:(BOOL)
于 2012-07-24T20:41:37.800 回答
49

要完全替换段,您可以使用以下函数:

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

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

希望这可以帮助。

于 2014-04-20T07:05:16.417 回答
31

这是一个小的 Swift 扩展,用新值数组替换当前的 segmentedControl

斯威夫特 3

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

斯威夫特 4

extension UISegmentedControl {
    func replaceSegments(segments: Array<String>) {
        self.removeAllSegments()
        for segment in segments {
            self.insertSegment(withTitle: segment, at: self.numberOfSegments, animated: false)
        }
    }
}
于 2015-12-03T15:44:55.583 回答
4

这是一个用字符串序列替换段的 Swift 扩展。它与此处给出的另一个答案相似,只是它可以与任何序列一起使用,这意味着您也可以传入切片、集合等。

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)
        }
    }
}
于 2017-04-06T18:20:38.757 回答
3

为了完整起见(并且因为我最终在这里寻找如何在 xib 中实现相同的功能)这里是如何在 xib 中做到这一点:

在此处输入图像描述

于 2014-11-13T23:07:45.080 回答
0

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

SEG_TipoFiltro.insertSegmentWithTitle("Title", atIndex: 2, animated: false)
于 2016-06-22T03:40:09.190 回答
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)
  }
}
于 2020-02-19T09:08:00.370 回答