iOS 自定義分段切換控件

圖1

圖2

以上就是實現(xiàn)的效果,支持左右滾動進行切換。
我們在實現(xiàn)上用到了Masonry 和UIView+LGJExtension,其中UIView+LGJExtension中包含了

@property (nonatomic, assign) CGPoint origin;
@property (nonatomic, assign) CGSize size;
@property (nonatomic, assign) CGFloat top;
@property (nonatomic, assign) CGFloat left;
@property (nonatomic, assign) CGFloat bottom;
@property (nonatomic, assign) CGFloat right;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;

以及其具體實現(xiàn)。
首先我們自定義LGJSegmentView 繼承UIView

#import <UIKit/UIKit.h>

@interface LGJSegmentView : UIView

@property(nonatomic,copy)void (^segmentClickBlock)(NSInteger index);

/**
 根據(jù)標(biāo)題個數(shù)進行初始化

 @param titles 標(biāo)題數(shù)組
 @return 創(chuàng)建好的視圖返回
 */
-(instancetype)initWithSegmentedTitles:(NSArray *)titles;


/**
 滾動到第幾個標(biāo)題處

 @param index 下表 0 1 2.。
 */
-(void)sliderToCurrentSelectedIndex:(NSInteger )index;

@end

在.m中聲明以下屬性

@property(nonatomic,strong)NSArray *titleArr;
@property(nonatomic,strong)NSMutableArray *buttonArr;
@property(nonatomic,strong)UIView *segmentedContainer;
@property(nonatomic,strong)UIView *sliderLine;
@property(nonatomic,strong)UIView *bottomLine;

同時,我們把控件距離左右邊的邊距,高,寬等也出去出來,方便改寫。

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define Margin 15
#define Height 40
#define LineWidth (ScreenWidth - Margin * 2)/(self.titleArr.count)

LGJSegmentedView.m

@implementation LGJSegmentView

-(instancetype)initWithSegmentedTitles:(NSArray *)titles{
    if (self = [super init]) {
        self.titleArr = titles;
        self.backgroundColor = [UIColor whiteColor];
        [self createSegmentView];
        [self setUpViews];
    }
    return self;
}

-(void)createSegmentView{
    self.buttonArr = [NSMutableArray array];
    for (int index = 0; index < self.titleArr.count; index++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [button setTitle:self.titleArr[index] forState:UIControlStateNormal];
        [button setTitle:self.titleArr[index] forState:UIControlStateSelected];
        [button setTitleColor:RGB_HEX(0x666666) forState:UIControlStateNormal];
        [button setTitleColor:RGB_HEX(0xff4400) forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        button.titleLabel.adjustsFontSizeToFitWidth = YES;
        if (index == 0) {
            button.selected = YES;
        }else{
            button.selected
            = NO;
        }
        button.tag = index;
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttonArr addObject:button];
    }
}


-(void)setUpViews{
    [self addSubview:self.segmentedContainer];
    for (UIButton *button in self.buttonArr) {
        [self.segmentedContainer addSubview:button];
    }
    [self addSubview:self.sliderLine];
    [self addSubview:self.bottomLine];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    self.segmentedContainer.top = 0;
    self.segmentedContainer.left = Margin;
    self.segmentedContainer.width = self.width - Margin*2;
    self.segmentedContainer.height = self.height;
    
    self.bottomLine.frame = CGRectMake(0, self.height-APPCONFIG_UNIT_LINE_WIDTH, self.width, APPCONFIG_UNIT_LINE_WIDTH);
    //每個子segment的寬度
    CGFloat segmentWith = (self.width-15*2) / self.buttonArr.count;
    for (int i=0; i<self.buttonArr.count; i++) {
        UIButton *button = (UIButton *)self.buttonArr[i];
        button.top = 0;
        button.left = i * segmentWith;
        button.width = segmentWith;
        button.height = Height;
    }
    //設(shè)置底部紅色滑動線條的位置
    self.sliderLine.bottom = self.bottomLine.top;
    self.sliderLine.left = self.segmentedContainer.left;
    self.sliderLine.width = segmentWith;
    self.sliderLine.height = 2.0f;
}


-(void)buttonClicked:(UIButton *)sender{
    [self selectedSegmentButton:sender];
    if (self.segmentClickBlock) {
        self.segmentClickBlock(sender.tag);
    }
}

-(void)selectedSegmentButton:(UIButton *)selectedButton{
    selectedButton.selected = YES;
    [self changeSelectedWithSelectedButton:selectedButton];
}

-(void)changeSelectedWithSelectedButton:(UIButton *)selectedButton{
    for (UIButton *button in _buttonArr) {
        if (![button isEqual:selectedButton]) {
            button.selected = NO;
        }
    }
    [self setSliderLinePosition];
}

-(void)setSliderLinePosition{
    UIButton *button = [self selectedButton];
    [UIView animateWithDuration:0.3f animations:^{
        self.sliderLine.left = Margin + button.tag * LineWidth;
    }];
}

-(UIButton *)selectedButton{
    NSInteger selIndex = [self selectedIndex];
    if (selIndex == -1 || self.buttonArr.count <= selIndex) {
        return nil;
    }
    return self.buttonArr[selIndex];
}
- (NSInteger)selectedIndex
{
    for(int i = 0; i < self.buttonArr.count; i++) {
        UIButton *button = (UIButton *)self.buttonArr[i];
        if (button.selected) {
            return i;
        }
    }
    return -1;
}

-(void)sliderToCurrentSelectedIndex:(NSInteger)index{
    UIButton *button = self.buttonArr[index];
    [self selectedSegmentButton:button];
}
#pragma mark - 懶加載
- (UIView *)segmentedContainer
{
    if (!_segmentedContainer) {
        _segmentedContainer = [[UIView alloc] init];
        _segmentedContainer.backgroundColor = [UIColor whiteColor];
    }
    return _segmentedContainer;
}

-(UIView *)sliderLine
{
    if (!_sliderLine) {
        _sliderLine = [[UIView alloc] init];
        _sliderLine.backgroundColor = RGB_HEX(0xff4400);
    }
    return _sliderLine;
}

-(UIView *)bottomLine
{
    if (!_bottomLine) {
        _bottomLine = [[UIView alloc] init];
        _bottomLine.backgroundColor = RGB_HEX(0xeeeeee);
    }
    return _bottomLine;
}

@end

在使用的時候也是很方便。多數(shù)時候我們會結(jié)合多個控制器來實現(xiàn)。這個時候往往的做法就是添加子控制器。

#pragma mark - 懶加載
[self.view addSubview:self.segment];

[self.view addSubview:self.scrollView];

[self.segment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(LGJNavigationBarAdapterContentInsetTop);
        make.size.mas_equalTo(CGSizeMake(APPCONFIG_UI_SCREEN_FWIDTH, 40));
    }];
 [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.segment.mas_bottom);
   }];
  self.scrollView.contentSize = CGSizeMake(self.childViewControllers.count*APPCONFIG_UI_SCREEN_FWIDTH, 0);


- (LGJSegmentView *)segment
{
    if (!_segment) {
        NSArray *titles = @[@"廣州",@"北京",@"上海",@"深圳"];
        _segment = [[LGJSegmentView alloc] initWithSegmentedTitles:titles];
        __weak typeof(self)weakSelf = self;
        _segment.segmentClickBlock = ^(NSInteger index) {
            // 讓底部的內(nèi)容scrollView滾動到對應(yīng)位置
            CGPoint offset = weakSelf.scrollView.contentOffset;
            offset.x = index * weakSelf.scrollView.frame.size.width;
            [weakSelf.scrollView setContentOffset:offset animated:YES];
        };
    }
    return _segment;
}
    //添加子控制器
    NSArray *titles = @[@"廣州",@"北京",@"上海",@"深圳"];
    for (int i=0; i<titles.count; i++) {
        LGJViewController *childCtrl = [[LGJViewController alloc] initWithChildViewType:i];
        [self addChildViewController:childCtrl];
    }

我們在點擊標(biāo)題進行切換,或者是滾動標(biāo)題以下視圖進行切換,需要綁定。

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    CGFloat width = scrollView.frame.size.width;
    CGFloat height = scrollView.frame.size.height;
    CGFloat offsetX = scrollView.contentOffset.x;
    // 當(dāng)前位置需要顯示的控制器的索引
    NSInteger index = offsetX / width;
    //設(shè)置optionalNewsSegment滾動到控制器對應(yīng)的位置
    [self.segment sliderToCurrentSelectedIndex:index];
    //容錯處理
    if (index<0) return;
    // 取出需要顯示的控制器
    LGJViewController *willShowVC = self.childViewControllers[index];
    // 如果當(dāng)前位置已經(jīng)顯示過了,就直接返回
    if ([willShowVC isViewLoaded]) return;
    // 添加控制器的view到scrollView中;
    willShowVC.view.frame = CGRectMake(offsetX, 0, width, height);
    [scrollView addSubview:willShowVC.view];
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,259評論 4 61
  • 2017-03-26 《精進》拆書片段01:克服天性中的選擇弱勢 R(P59) I 現(xiàn)在人們面臨的選擇太多太多,多...
    李先森2016閱讀 306評論 0 0
  • 在文友“云上人”30天連續(xù)寫作訓(xùn)練總結(jié)中,我被她比喻為“向日葵”:善解人意、光明溫暖的向日葵,就像一個溫暖的小太陽...
    清露靜心閱讀 326評論 1 6
  • 模式定義 定義一個用于創(chuàng)建對象的接口,讓子類決定實例化哪一個類,工廠方法使一個類的實例化延遲到其子類。 模式結(jié)構(gòu) ...
    忘凈空閱讀 317評論 0 1