Ios 重用段控件
我做了一个像这样的段控制Ios 重用段控件,ios,swift,uisegmentedcontrol,Ios,Swift,Uisegmentedcontrol,我做了一个像这样的段控制 import UIKit enum HomeOptions: String, RawRepresentable { case ViewAll, News, Articles, Post, Offers var title: String { switch self { case .ViewAll: return "View All" case .News: return "News" case .Art
import UIKit
enum HomeOptions: String, RawRepresentable {
case ViewAll, News, Articles, Post, Offers
var title: String {
switch self {
case .ViewAll:
return "View All"
case .News:
return "News"
case .Articles:
return "Articles"
case .Post:
return "Post"
case .Offers:
return "Offers"
}
}
}
Enums.swift
的类,就像这样
import UIKit
enum HomeOptions: String, RawRepresentable {
case ViewAll, News, Articles, Post, Offers
var title: String {
switch self {
case .ViewAll:
return "View All"
case .News:
return "News"
case .Articles:
return "Articles"
case .Post:
return "Post"
case .Offers:
return "Offers"
}
}
}
3.在viewController的viewDidLoad
中,我添加了以下行
homeSegment.selectedSegmentIndex = 0
homeSegment.setTitle(HomeOptions.ViewAll.title, forSegmentAt: 0)
homeSegment.setTitle(HomeOptions.News.title, forSegmentAt: 1)
homeSegment.setTitle(HomeOptions.Articles.title, forSegmentAt: 2)
homeSegment.setTitle(HomeOptions.Post.title, forSegmentAt: 3)
homeSegment.setTitle(HomeOptions.Offers.title, forSegmentAt: 4)
现在,这些代码行在相应的段中设置适当的名称
但我担心的是
如果我需要在应用程序的其他地方添加另一个段控件,比如3个段和不同的段选项,那么我不想在该视图中拖动另一个段控件并再次重复上述代码/过程。但是我只想在应用程序中的某个地方添加/拖动段控件一次,并在枚举中包含其他选项(段控件),并在必要时使用它们。我能做到吗 你可以用这个,
请注意,添加标题时将使用您发送选项的顺序
func getSegmentControl(with options: [HomeOptions]) -> UISegmentedControl{
let segmentControl = UISegmentedControl.init()
for i in 0..<options.count {
segmentControl.setTitle(option.title, forSegmentAt: i)
}
//do additional operations here
return segmentControl
}
func-getSegmentControl(带选项:[homeooptions])->UISegmentedControl{
让segmentControl=UISegmentedControl.init()
对于0..中的i,您可以创建如下UISegmentControl:
let segmentControl = UISegmentedControl.init()
for i in 0..<yourOptions.count {
let option = yourOptions[i]
segmentControl.setTitle(option.title, forSegmentAt: i)
}
segmentControl.frame = yourDesiredFrame
yourView.addSubView(segmentControl)
let segmentControl=UISegmentedControl.init()
对于0中的i..那么您必须以编程方式创建它ok…关于如何@Shahzaib Qureshi..有什么建议吗?您可以发送数组中的主选项并返回视图。循环类型HomeOptions的数组并将其全部添加。好的..但这是针对选项的权利..我如何重用段控件..@Nareshfor,您可以使用单音按钮谢谢s、 老兄,我刚去了。