Mar-05-2020 17-06-17.gif
-(void)reloadCategory{
if (self.btnsArray.count >0) {
[self.btnsArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj removeFromSuperview];
}];
}
[self.categoryNewsArray enumerateObjectsUsingBlock:^(NewsCategoryModel *categoryModel, NSUInteger idx, BOOL * _Nonnull stop) {
UIButton *btn = [self categoryBtnWithTag:idx selected:self.selectIndex=idx?NO:YES title:categoryModel.categoryName];
CGFloat w = [UILabel getWidthWithText:btn.titleLabel.text height:53 fontSize:btn.titleLabel.font];
[btn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:btn];
[self.btnsArray addObject:btn];
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.scrollView);
if (idx == 0) {
make.left.equalTo(self.scrollView).offset(10);
}
else
{
UIButton *lastBtn = self.btnsArray[idx-1];
make.left.equalTo(lastBtn.mas_right);
}
make.width.equalTo(@(w+30));
make.height.equalTo(@(53));
}];
}];
[self.scrollView layoutIfNeeded];
UIButton *btn = self.btnsArray.lastObject;
self.scrollView.contentSize =CGSizeMake(btn.ly_x+btn.ly_width+10,0);
}
-(void)clickAction:(UIButton *)sender{
self.selectIndex = sender.tag;
self.pageNum = 0;
[self pullNews];
[self.btnsArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[self selectStyle:idx == sender.tag?YES:NO withBtn:obj];
}];
//点击之后一直居中,动画保持居中
CGPoint startPoint = [self.view convertPoint:sender.center fromView:sender.superview];
CGFloat offset = startPoint.x - SIZE.width/2;
CGFloat totaloffset = self.scrollView.contentOffset.x+offset;
if(totaloffset < 0){
totaloffset = 0;
}
if (totaloffset > self.scrollView.contentSize.width-SIZE.width) { //判断是否是高于最后一页
totaloffset = self.scrollView.contentSize.width-SIZE.width;
}
[self.scrollView setContentOffset:CGPointMake(totaloffset, 0)];
}
-(UIButton *)categoryBtnWithTag:(NSInteger)tag selected:(BOOL)isSelected title:(NSString *)titleStr{
UIButton *btn = [[UIButton alloc] init];
btn.tag = tag;
[self.scrollView addSubview:btn];
[self selectStyle:isSelected withBtn:btn];
[btn setTitle:titleStr forState:UIControlStateNormal];
return btn;
}
-(NSMutableArray *)btnsArray
{
if (!_btnsArray) {
_btnsArray = [[NSMutableArray alloc] init];
}
return _btnsArray;
}
-(void)selectStyle:(BOOL)isSelected withBtn:(UIButton *)sender{
if (isSelected) {
[sender setTitleColor:Color_169FAC forState:UIControlStateNormal];
sender.titleLabel.font = Font_b_20;
}
else
{
[sender setTitleColor:Color_777777 forState:UIControlStateNormal];
sender.titleLabel.font = Font_b_16;
}
}
网友评论