iOS開源:SegmentedControl-可以自定義設置 UI 的 Segmented Control

DanielBogen 7年前發布 | 14K 次閱讀 開源 iOS開發 移動開發

這是我近期完成的一個項目,目前還在尋找那些沒有被我發現的 BUG。

YUSegment 是一個可以自定義設置 UI 的 Segmented Control,盡可能保留了原生 UISegmentedControl 的接口。

demo.gif

Features

  • 支持 (Attributed)text 和 image
  • 有兩種(線形和圓角矩形的指示器)不同的樣式可以選擇
  • 支持橫向滾動
  • 需要 iOS 8.0+,支持 ARC

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;
  4. 你可以在 Attributes Inspector 修改其他的屬性。

    storyboard3.png

APIs

Target-Action

和 UISegmentedControl 類似,你只需要使用以下的代碼:

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

Attributed Text

YUSegment 沒有實例方法能夠直接將一個 attributed string 作為參數,你需要通過 -setTitleTextAttributes:forState: 方法來設置 attributed string。

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

Layer

你可以在 Attributes Inspector 設置 borderColor , borderWidth , cornerRadius 等屬性,如果通過代碼的方式來設置這些屬性,可以想下面這樣:

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

需要注意的是:你需要通過 cornerRadius 而不是 layer.cornerRadius 來設置圓角,因為前者會自動為指示器設置上圓角。

segment.cornerRadius = someValue;

Scrolling Enabled

YUSegment 沒有類似 scrollEnabled 的屬性,如果你要使 segmented control 能夠橫向滾動,你需要設置 segmentWidth 的值,該屬性能夠自動使 segmented control 支持橫向滾動。

 

 

 本文由用戶 DanielBogen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!