UISegmentedControl以编程方式更改段数


Answers:


136

是的,您可以使用

removeSegmentAtIndex:(NSUInteger) animated:(BOOL)

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

我解决了:[self.SegmentAnswer insertSegmentWithTitle:@“ 5” atIndex:4 animation:YES]; [self.SegmentAnswer insertSegmentWithTitle:@“ 6” atIndex:5
Beppino66

46

要完全替换段,可以使用以下功能:

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

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

希望这可以帮助。


2
这非常适合放入UISegmentedControl类别。谢谢!
DonnaLea 2014年

1
您可以使用[segmentController removeAllSegments]代替while循环。请参阅developer.apple.com/library/ios/documentation/UIKit/Reference/…上
MCR

要仔细检查,它适用于7.X和8.X吗?
佐拉尔

编辑使用[segmentController removeAllSegments] 按@ MCR的评论。
佐拉尔

27

这是一个小的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)
        }
    }
}

3

为了完整起见(并且因为我最后在这里寻找如何在xib中实现相同的目的),这里是在xib中的操作方法:

在此处输入图片说明


3

这是一个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)
        }
    }
}

1
您可以添加指向您所指的其他答案的链接吗?您可以通过单击下面的“共享”链接来获得答案的永久链接。
Al Sweigart'4

0

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

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

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)
  }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.