ios零碎记录UIKitios

开源一个 SegmentedControl

2016-12-19  本文已影响1935人  afishhhhh

这是我近期完成的一个项目,目前还在寻找那些没有被我发现的 BUG。

地址:YUSegment

YUSegment 是一个可以自定义设置 UI 的 Segmented Control,尽可能保留了原生 UISegmentedControl 的接口。

demo.png

Features

Installation

Cocoapods

  1. 在 Podfile 中添加 pod 'YUSegment'
  2. 执行 pod install 命令
  3. 导入头文件 #import "YUSegment.h"

Usage

可以通过 Storyboard 和 纯代码的方式创建一个 YUSegment。

Code(推荐)

NSArray *titles = @[@"Left", @"Medium", @"Right"];
YUSegment *segment = [[YUSegment alloc] initWithTitles:titles];
[self.view addSubview:segment];
segment.frame = (CGRect){20, 60, [UIScreen mainScreen].bounds.size.width - 40, 44};

Storyboard

  1. 从 Object Library 拖拽一个 "UIView" 到 storyboard.
  2. 修改 view 的位置和大小


    storyboard2.png
  3. 在 Identify Inspector 中将 class 修改为 YUSegment,然后建立一个 outlet。


    storyboard1.png
@property (weak, nonatomic) IBOutlet YUSegment *segment;
  1. 你可以在 Attributes Inspector 修改其他的属性。


    storyboard3.png

更多的例子可以参考 YUSegmentDemo

APIs

Target-Action

和 UISegmentedControl 类似,你只需要使用以下的代码:

[segment addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventValueChanged];

Images

在默认的情况下,如果 segment 的内容有图片,无论当前的 segment 有没有被选中,都是展示相同的图片。可以调用 -replaceDeselectedImages: 或者 -replaceDeselectedImageWithImage:atIndex: 替换掉未选中状态下的图片。

Attributed Text

YUSegment 没有实例方法能够直接将一个 attributed string 作为参数,你需要通过 -setTitleTextAttributes:forState: 方法来设置 attributed string。

NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:20]};
[segment setTitleTextAttributes:attributes forState:YUSegmentedControlStateNormal];

Layer

你可以在 Attributes Inspector 设置 borderColorborderWidthcornerRadius 等属性,如果通过代码的方式来设置这些属性,可以像下面这样:

segment.layer.borderWidth = someValue;
segment.layer.borderColor = someValue;

需要注意的是:你需要通过 cornerRadius 而不是 layer.cornerRadius 来设置圆角,因为前者会自动为指示器设置上圆角。

Scrolling Enabled

YUSegment 没有类似 scrollEnabled 的属性,如果你要使 segmented control 能够横向滚动,你需要设置 segmentWidth 的值,该属性能够自动使 segmented control 支持横向滚动。

New Features:

Version 0.1.4:
segment.borderWidth(1.0).borderColor([UIColor redColor]);
Version 0.2.0:
segment.indicator.backgroundColor = [UIColor redColor];
segment.indicator.layer.borderWidth = 1.0;
segment.indiactor.layer.borderColor = [UIColor redColor].CGColor;
segment.indicator.borderWidth(1.0).borderColor([UIColor redColor]);

如果大家觉得 YUSegment 还可以,就给一个 star 吧😀😀😀。

上一篇 下一篇

猜你喜欢

热点阅读