重用段控件

问题描述 投票:-1回答:2

我做了一个像这样的段控制......

  1. 我已将一个段控件拖到故事板中的视图控制器中,并将其分为5段。

我做了一个叫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个段和不同的段选项,那么我不想在该视图中拖动另一个段控件并再次重复上述代码/过程。但我想在应用程序中的某个位置添加/拖动段​​控件一次,并在枚举中包含其他选项(段控件)并在必要时使用它们。我可以实现吗?

ios swift uisegmentedcontrol
2个回答
0
投票

您可以使用此功能,注意添加标题时将使用您发送选项的顺序。

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
}

建议 - 将枚举的名称从HomeOptions更改为HomeOption。


0
投票

您可以像这样创建分段控件:

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)

这里的yourOptions是Options数组,yourDesiredFrame是你希望UISegmentControl拥有的框架,yourView是你想要添加这个UISegmentControl的视图。

© www.soinside.com 2019 - 2024. All rights reserved.