HSegmentControl 2.1.2

HSegmentControl 2.1.2

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最新发布2017年6月
SwiftSwift 版本3.0
SPM支持 SPM

Hao维护。



  • Chang, Hao

HSegmentControl

HSegmentControl 是一个自定义的分段控件子类,继承自 UIControl,其中视图、每个分段的标题和指示视图都可以自定义。

特性

  • [x] 可自定义的配置
    • @IBInspectable标题颜色
    • @IBInspectable指示图
    • @IBInspectable显示的段数
    • 标题字体
    • 指示视图

  • [x] 数据源协议
    • 段数
    • 段背景视图(可选)

  • [x] 文档

示例

例子

要运行示例项目,首先克隆仓库,然后从 Example 目录中运行 pod install

安装

HSegmentControl 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile:

pod "HSegmentControl"
Swift 版本 版本
2.3 2.0.x
3.0 2.1.0 或更高版本

用法

添加到视图

您可以通过代码来以编程方式添加 HSegmentControl

let segmentControl = HSegmentControl()
view.addSubview(segmentControl)
// Customized configuration
// .
// .
// .

或者直接在 Storyboard(Interface Builder)中拖放一个 UIView,将其类设置为 HSegmentControl

数据源协议

确保您的控制器实现了 HSegmentControlDataSource 协议并将其设置为 HSegmentControldataSource

class ViewController: UIViewController, HSegmentControlDataSource{
    // .
  // .
  // .
  override func viewDidLoad(){
        super.viewDidLoad()   
        segmentControl.dataSource = self
        //.
      //.
      //.
  }
    // .
  // .
  // .
  // MARK: - HSegmentControlDataSource protocol
    func numberOfSegments(segmentControl: HSegmentControl) -> Int {
        return 5
    }
    
    func segmentControl(segmentControl: HSegmentControl, titleOfIndex index: Int) -> String {
        return ["1","two", "threeeeeee", "four", "five"][index]
    }
    
    // Optional
    func segmentControl(segmentControl: HSegmentControl, segmentBackgroundViewOfIndex index: Int) -> UIView {
        let view = UIView()
        view.backgroundColor = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1)
        return view
    }
}

配置 HSegmentControl

override func viewDidLoad(){
    super.viewDidLoad()
    segmentControl.dataSource = self
    //.
  //.
  //.
  // Customized configuration
  segmentControl.numberOfDisplayedSegments = 3
    segmentControl.selectedTitleFont = UIFont.boldSystemFontOfSize(17)
    segmentControl.selectedTitleColor = UIColor.darkGrayColor()
    segmentControl.unselectedTitleFont = UIFont.systemFontOfSize(17)
    segmentControl.unselectedTitleColor = UIColor.blackColor()
    segmentControl.segmentIndicatorImage = UIImage(named: "ind_img")
    segmentControl.segmentIndicatorViewContentMode = UIViewContentMode.Bottom
    segmentControl.segmentIndicatorView.backgroundColor = UIColor.whiteColor()
}

值变化

与任何其他 UIControl 一样,将 valueChanged 函数连接到代理动作。

@IBAction func valueChanged(sender: AnyObject){
    print("value did change to \((sender as! HSegmentControl).selectedIndex)")
}

手动更改值

只需设置 selectedIndex 变量

segmentControl.selectedIndex = 2

请注意,当您手动设置 selectedIndex 时,不会调用 valueChanged(sender:) 函数。

作者

许可

HSegmentControl 在 MIT 许可证下可用。更多信息请参阅 LICENSE 文件。