有没有办法以编程方式更改段数?
Answers:
要完全替换段,可以使用以下功能:
- (void)setSegments:(NSArray *)segments
{
[segmentController removeAllSegments];
for (NSString *segment in segments) {
[segmentController insertSegmentWithTitle:segment atIndex:segmentController.numberOfSegments animated:NO];
}
}
希望这可以帮助。
[segmentController removeAllSegments]
按@ MCR的评论。
这是一个小的Swift扩展,用新值数组替换当前的segmentedControl
extension UISegmentedControl {
func replaceSegments(segments: Array<String>) {
self.removeAllSegments()
for segment in segments {
self.insertSegmentWithTitle(segment, atIndex: self.numberOfSegments, animated: false)
}
}
}
extension UISegmentedControl {
func replaceSegments(segments: Array<String>) {
self.removeAllSegments()
for segment in segments {
self.insertSegment(withTitle: segment, at: self.numberOfSegments, animated: false)
}
}
}
为了完整起见(并且因为我最后在这里寻找如何在xib中实现相同的目的),这里是在xib中的操作方法:
这是一个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)
}
}
}
为我工作,UIsegmentedControll包含两个部分,我想在索引2中添加一个,在swift 2.2中使用此代码使用:
SEG_TipoFiltro.insertSegmentWithTitle("Title", atIndex: 2, animated: false)
使用代码在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)
}
}