精华界面按钮与滚屏联动

1. 滚屏显示跟随按钮

  • 监听按钮点击事件方法中修改 scrollView 的偏移量, 既是修改显示
// 监听按钮点击事件
- (void)clickTitleButton:(UIButton *)titleButton{
    _previousClickTitleButton.selected = NO; 
    titleButton.selected = !titleButton.selected;
    _previousClickTitleButton = titleButton;

    // 修改偏移量
    CGPoint Offset = _scrollView.contentOffset;
    Offset.x = titleButton.tag * _scrollView.CDH_width;

    [UIView animateWithDuration:0.3 animations:^{
        _titleUnderline.CDH_width = titleButton.titleLabel.CDH_width + 10;
        _titleUnderline.CDH_centerX = titleButton.CDH_centerX;
        _scrollView.contentOffset = Offset;
    }];
}

2. 按钮跟随显示:

  • 监听 scrollView 的滑动显示的当前可视范围, 修改按钮选中显示

  • 方法一:

    • 在滑动完毕的时候调用的方法计算出对应的索引, 根据索引找到对应的子控件找到对应的按钮, 再调用点击按钮方法点击按钮
    /** scrollView滑动完毕的时候调用(速度减为0的时候调用) */
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
        NSInteger index = scrollView.contentOffset.x / scrollView.xmg_width;
        // 方法一:
        CDHTitleButton *titleButton = self.titlesView.subviews[index];
        // 方法二:
    //    CDHTitleButton *titleButton = [self.titlesView viewWithTag:index];
        [self titleButtonClick:titleButton];
    }
    
  • 方法二:

    • 在滑动完毕的时候调用的方法计算出对应的索引, 在根据索引 viewWithTag: 方法遍历 titlesView 中的所有索引对应的 tag标识
    • [self.titlesView viewWithTag:index]返回一个按钮,
    • 再使用返回的按钮做参数, 调用按钮点击的方法;
    • 注意: 要给你父控件也绑定标识, 如果没有给父控件制定 tag , 则默认是0, 这时候如果第一个按钮的标识也是0, 上面的 viewWithTag: 这个方法先变遍历了父控件自己的标识, 标识相同则直接返回父控件, 使用返回的父控件调用点击的方法, 方法中没有按钮对应的方法, 程序就崩溃了
    • 注意: viewWithTag: 这个方法是递归方法, 返回值包括自己, 遍历顺序是: 先自己, 再到子控件, 只要符合要求则直接返回;
    • 递归遍历: 如果某个子控件中的又有子控件, 则遍历了该子控件之后还不符合要求, 则接着就会进入到某子控件中遍历, 只有遍历完某子控件中的子控件都不符合要求, 才会回到和某子控件同级的下一个子控件......
    // viewWithTag: 方法的伪代码还原实现原理
    @implementation UIView
    - (UIView *)viewWithTag:(NSInteger)tag{
    
        // 如果自己的tag符合要求, 就返回自己
        if (self.tag == tag) return self;
        // 遍历子控件,查找tag符合要求的子控件
        for (UIView *subview in self.subviews) {
    //        if (subview.tag == tag) return subview;
            UIView *resultView = [subview viewWithTag:tag];
            if (resultView) return resultView;
        }
        // 找不到符合要求的子控件
        return nil;
    }
    @end
    
  • 如果调用了不属于自己有的方法会出现的错误

    /*
     -[UIView setSelected:]: unrecognized selector sent to instance 0x7ff3f35b1070
    
     -[CDHPerson length]: unrecognized selector sent to instance 0x7ff3f35b1070
     错误将CDHPerson当做NSString来使用,比如
     id obj = [[CDHPerson alloc] init];
     NSString *string = obj;
     string.length;
    
     -[CDHPerson count]: unrecognized selector sent to instance 0x7ff3f35b1070
     id obj = [[CDHPerson alloc] init];
     NSArray *array = obj;
     array.count;
    
     -[CDHPerson setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x7ff3f35b1070
     错误将CDHPerson当做NSMutableDictionary来使用
    
     规律: 方法名里面包含了Subscript的方法,一般都是集合的方法(比如字典\数组)
    */
    

results matching ""

    No results matching ""