1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//
// WYSegmentView.h
// GengMei
//
// Created by wangyang on 13-8-9.
// Copyright (c) 2015 Gengmei. All rights reserved.
//
#import "WYSegmentView.h"
#import <QuartzCore/QuartzCore.h>
#import <Masonry/Masonry.h>
#import "UIView+Layout.h"
#import <Constant.h>
#import "UIView+LineWithAutolayout.h"
#import "GMFont.h"
#import <UIColor+GMTheme.h>
#import "GMButton.h"
#import "UIDevice+Resolutions.h"
#import "UIButton+WebCache.h"
#import "UIImage+MultiFormat.h"
#import "UIImageView+WebCache.h"
#define BUTTON_TAG 1010
@interface WYSegmentView ()
{
UIView *_indicatorView;
UIView *_container;
}
@property (nonatomic, assign) NSInteger selectedSegmentIndex;
@end
@implementation WYSegmentView
- (void)setup
{
[super setup];
_bothEndPadding = ([UIDevice resolutionType] <= iPhone40Inches) ? 12 : 16;
_bottomLine = [self addBottomLine];
// scroll view
_scrollView = [UIScrollView new];
[self addSubview:_scrollView];
[_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.insets(UIEdgeInsetsZero);
}];
// container
_container = [UIView new];
[_scrollView addSubview:_container];
[_container mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.insets(UIEdgeInsetsZero);
}];
// 属性初始化
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
self.indicatorHorizonalPadding = 7.5 * ONE_PIXEL;
self.titleTextAttributes = @{NSFontAttributeName : [UIFont gmFont:15],
NSForegroundColorAttributeName : UIColor.whiteColor};
self.selectedTitleTextAttributes = @{NSFontAttributeName : [UIFont gmFont:15],
NSForegroundColorAttributeName : [UIColor auxiliaryTextGreen]};
self.showIndicator = NO;
self.indicatorColor = UIColor.auxiliaryTextGreen;
self.widthStyle = WYSegmentViewWidthStyleDynamic;
_selectedSegmentIndex = 0;
// 添加指示器
[self setupIndicatorView];
}
- (void)setupIndicatorView {
_indicatorView = [UIView new];
_indicatorView.backgroundColor = self.indicatorColor;
[_scrollView insertSubview:_indicatorView atIndex:0];
__weak __typeof(self)weakSelf = self;
self.updateIndicatorFrame = ^(UIView *indicator, UIButton *button) {
// 在 _sectionTitles 还没有数据时,button 并没有被添加,会是 nil, 所以添加如下判断
if (button == nil || indicator == nil) {
return;
}
// 改变indicator
indicator.frame = CGRectMake(button.titleLabel.width * 1 / 6, indicator.superview.height - 9, button.titleLabel.width * 2 / 3, 3);
indicator.centerX = button.centerX;
indicator.layer.cornerRadius = 1 + ONE_PIXEL;
indicator.layer.masksToBounds = YES;
indicator.layer.shadowColor = weakSelf.indicatorColor.CGColor;
indicator.layer.shadowOpacity = 0.35;
indicator.layer.shadowOffset = CGSizeMake(0,1);
indicator.layer.shadowRadius = 1;
indicator.clipsToBounds = NO;
};
}
- (void)setupSegments {
[_container removeAllSubviews];
// button间距,在 WYSegmentViewWidthStyleFixed 中会用到。顺便创建buttons
CGFloat space = 0;
CGFloat allTitleSize = 0;
for (int i = 0; i < _sectionTitles.count; i++) {
GMButton *button = [GMButton buttonWithType:UIButtonTypeCustom];
button.tag = i + BUTTON_TAG;
button.enableAdaptive = YES;
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
NSString *title = _sectionTitles[i];
NSAttributedString *attriTitle = [[NSAttributedString alloc] initWithString:title attributes:self.titleTextAttributes];
NSAttributedString *seletedAttriTitle = [[NSAttributedString alloc] initWithString:title attributes:self.selectedTitleTextAttributes];
__block CGFloat btnW = [seletedAttriTitle size].width;
CGFloat btnTitleH = [seletedAttriTitle size].height;
if (self.sectionTitlesInfor != nil &&
self.sectionTitlesInfor.count > i &&
[self.sectionTitlesInfor[i] isKindOfClass:[NSDictionary class]] &&
((GMSegmentBtnStyle)[(self.sectionTitlesInfor[i][@"btnStyle"]) integerValue]) == GMSegmentBtnStyleLive) {
NSString *imgurl = self.sectionTitlesInfor[i][@"tabNameImage"];
if (imgurl && imgurl.length > 0) {
__block CGFloat imgW = 32;
CGFloat imgH = btnTitleH;
UIImageView *contentIv = [UIImageView new];
[button addSubview:contentIv];
contentIv.tag = 1;
[contentIv sd_setImageWithURL:[NSURL URLWithString:imgurl] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
// 防止多次下载同一张图片,上次下载被取消后返回nil的造成的carsh
if (image == nil) return;
// 如果该button已经被移除了,就不再进行约束更新操作
if (contentIv.superview.superview == nil) return;
imgW = ceil((image.size.width * 40)/image.size.height);
[contentIv mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(imgW);
}];
btnW = imgW;
}];
[contentIv mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(imgW);
make.height.mas_equalTo(40);
make.center.mas_equalTo(button.center);
}];
NSString *iconUrl = self.sectionTitlesInfor[i][@"iconUrl"];
if (iconUrl && iconUrl.length > 0) {
UIImageView *liveIv = [UIImageView new];
liveIv.tag = 2;
__block CGFloat liveIvW = 40;
[liveIv sd_setImageWithURL:[NSURL URLWithString:iconUrl] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
// 防止多次下载同一张图片,上次下载被取消后返回nil的造成的carsh
if (image == nil) return;
// 如果该button已经被移除了,就不再进行约束更新操作
if (liveIv.superview.superview == nil) return;
liveIvW = (image.size.width * 40.0)/image.size.height;
[liveIv mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(liveIvW);
}];
}];
liveIv.clipsToBounds = NO;
[button addSubview:liveIv];
[liveIv mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(liveIvW);
make.height.mas_equalTo(40);
make.left.mas_equalTo(contentIv.mas_right).mas_offset(-7);
make.centerY.mas_equalTo(contentIv.centerY);
}];
}
}else{
// 如果是Live类型,但是没有图片url,则不显示该btn
btnW = 0;
button.alpha = 0;
}
}else{
[button setAttributedTitle:attriTitle forState:UIControlStateNormal];
[button setAttributedTitle:seletedAttriTitle forState:UIControlStateSelected];
}
[_container addSubview:button];
button.width = btnW;
allTitleSize += button.width;
}
// 为buttons添加约束信息
UIView *preView;
space = (self.width - allTitleSize - _bothEndPadding * 2) / (_sectionTitles.count + 1); // 计算间距
for (int i = 0; i < _sectionTitles.count; i++) {
GMButton *button = _container.subviews[i];
[button mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(_container).offset(_scrollView.contentInset.top);
make.bottom.equalTo(_container).offset(-_scrollView.contentInset.bottom);
make.height.equalTo(_scrollView).offset(-_scrollView.contentInset.top - _scrollView.contentInset.bottom);
if (self.widthStyle == WYSegmentViewWidthStyleFixed) { // 之前的全局统一样式:固定样式
make.width.mas_equalTo(button.width);
if (i == 0) {
make.left.mas_equalTo(space + _bothEndPadding);
}else {
make.left.equalTo(preView.mas_right).offset(space);
}
if (i == _sectionTitles.count-1) {
make.right.mas_equalTo(-space - _bothEndPadding);
}
}else if(self.widthStyle == WYSegmentViewWidthStyleEqual) { // 新添加的全局统一样式:均分样式
make.width.mas_equalTo(self.width / _sectionTitles.count);
if (i == 0) {
make.left.mas_equalTo(0);
}else {
make.left.equalTo(preView.mas_right);
}
if (i == _sectionTitles.count-1) {
make.right.mas_equalTo(0);
}
}else { // 动态样式
// button.width == 0 兼容 非文字的btn并且未获取到图片url的情况
make.width.mas_equalTo(button.width > 0 ? ceilf(button.width + _itemHorizonalPadding * 2) : 0);
if(i == 0) {
make.left.mas_equalTo(0);
}else {
make.left.equalTo(preView.mas_right);
}
if (i == _sectionTitles.count-1) {
make.right.mas_equalTo(0);
}
}
}];
if (self.customButtonUI) {
self.customButtonUI(button, i);
}
preView = button;
}
}
#pragma mark - Setter
/**
* 清除原来的 button,并依据 title array 重新添加 button
*
* @param sectionTitles 待显示的 title array
*/
- (void)setSectionTitles:(NSArray *)sectionTitles
{
if (sectionTitles.count == 0) {
return;
}
_sectionTitles = sectionTitles;
[_container.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}
- (void)setShowIndicator:(BOOL)showIndicator {
_showIndicator = showIndicator;
_indicatorView.hidden = !_showIndicator;
}
- (void)setIndicatorColor:(UIColor *)indicatorColor {
_indicatorColor = indicatorColor;
_indicatorView.backgroundColor = _indicatorColor;
}
- (void)setSectionTitlesInfor:(NSArray *)sectionTitlesInfor
{
if (sectionTitlesInfor.copy == 0) {
return;
}
_sectionTitlesInfor = sectionTitlesInfor;
}
#pragma mark - Layout Views
- (void)layoutSegments
{
[self setupSegments];
[self setSelectedSegmentIndex:_selectedSegmentIndex animated:NO];
}
#pragma mark - Animation
- (void)animateSelectedButtonBackgroundAtIndex:(NSUInteger)index animate:(BOOL)animate
{
// 将 _indicatorView 移动到相应 button 位置
UIButton *currentButton = (UIButton *)[_container viewWithTag:index + BUTTON_TAG];
[UIView animateWithDuration:(animate ? 0.25 : 0.0) animations:^{
// 改变offset
// 当rect的中心点大于scrollview的中心点,那就可以把这个button往中间移一下
if ((_scrollView.contentSize.width > _scrollView.width)) {
if (CGRectGetMidX(currentButton.frame) > self.width / 2) {
// 下面这个算法是基于offset为0的情况
CGFloat offset = CGRectGetMidX(currentButton.frame) - self.width / 2;
CGFloat maxOffset = _scrollView.contentSize.width - self.width + _scrollView.contentInset.right;
if (offset > maxOffset) {
offset = maxOffset;
}
_scrollView.contentOffset = CGPointMake(offset, 0);
}else {
_scrollView.contentOffset = CGPointMake(-_scrollView.contentInset.left, 0);
}
}
// 改变indicator的坐标
if (self.updateIndicatorFrame) {
self.updateIndicatorFrame(_indicatorView, currentButton);
}
}];
}
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex animated:(BOOL)animated {
// 通过使用 selectedIndex 的 set 方法来执行button选择状态的 UI 变化,详见其 set 方法
[self changeStatusForePreButton:self.selectedSegmentIndex newButton:selectedSegmentIndex];
// 改变属性值
_selectedSegmentIndex = selectedSegmentIndex;
// 调用动画
[self animateSelectedButtonBackgroundAtIndex:selectedSegmentIndex animate:animated];
}
- (void)changeStatusForePreButton:(NSInteger)preButtonIndex newButton:(NSInteger)newButtonIndex{
// 取消先前 button 的状态
UIButton *previousbutton = (UIButton *)[_container viewWithTag:preButtonIndex + BUTTON_TAG];
previousbutton.selected = NO;
// 处理新的 button
UIButton *currentButton = (UIButton *)[_container viewWithTag:newButtonIndex + BUTTON_TAG];
currentButton.selected = YES;
// 立即变更button状态,以防之后的动画影响button title的改变
[self layoutIfNeeded];
}
#pragma mark - Action
- (void)buttonClick:(UIButton *)button
{
[self setSelectedSegmentIndex:button.tag - BUTTON_TAG animated:YES];
if (_didSelectedBlock) {
_didSelectedBlock(self.selectedSegmentIndex);
}
}
@end