在做一個(gè)scrollView上有兩個(gè)tableView時(shí),想左滑右滑時(shí)tableView會(huì)滑動(dòng)切換,在這里需要注意的是:
1、scrollView 的 contentsize 高度可以設(shè)置為0 ,這樣就不會(huì)在滑動(dòng)時(shí)出現(xiàn)上下晃動(dòng);
2、scrollView的屬性pagingEnabled = yes,這樣在滑動(dòng)時(shí)就會(huì)一頁一頁的滑動(dòng);
_homeScrollView = [[UIScrollView alloc] init];
//設(shè)置ScrollView內(nèi)容展示的大小
_homeScrollView.contentSize = CGSizeMake(WIDTH * 2 , 0);
_homeScrollView.bounces = NO;
_homeScrollView.pagingEnabled = YES;
_homeScrollView.delegate = self;
[self.view addSubview:_homeScrollView];
然后在上方有兩個(gè)按鈕,想著就是滑動(dòng)的時(shí)候按鈕的選中狀態(tài)也在改變,在這里卡了蠻久的。最后整理一下:
1、首先Button在定義的時(shí)候,設(shè)置選中狀態(tài)和正常狀態(tài);
比如:
//正常狀態(tài)的背景顏色
_liftButton.backgroundColor = [UIColor colorWithRed:206/255.0 green:206/255.0 blue:206/255.0 alpha:1];
//設(shè)置Button上的字和顏色
[_liftButton setTitle:@"公告" forState:UIControlStateNormal];
[_liftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//設(shè)置Button選中狀態(tài)的背景顏色(圖片)
[_liftButton setBackgroundImage:[UIImage imageNamed:@"按鈕選中背景"] forState:UIControlStateSelected];
在這里之前出現(xiàn)過的問題:
setbackgroundImage 寫成setImage 后每次都看不到Button上的字,搞了半天,各種換背景,透明,什么的,最后發(fā)現(xiàn)是方法寫錯(cuò)了,以后警戒。
接著是Button的點(diǎn)擊事件,需要設(shè)置一個(gè)中間Button來接收自己上一回點(diǎn)中的Button,首先判斷點(diǎn)擊的button是不是上回點(diǎn)擊的,然后將點(diǎn)擊的Button置為選中,上一回的置為非選中。
//按鈕點(diǎn)擊事件
-(void)buttonSelected:(UIButton *)sender{
if (sender!=_tempButton) {
sender.selected = YES;
_tempButton.selected = NO;
_tempButton =sender;
//此方法設(shè)置Button點(diǎn)擊后tableView跳轉(zhuǎn),動(dòng)畫以0.5倍的速度
//偏移量為Button.tag - 100
//因?yàn)锽utton.tag = 100
[UIView animateWithDuration:0.5 animations:^{
_homeScrollView.contentOffset = CGPointMake((sender.tag-100)*WIDTH, 0);
}];
}
}
這里tag值設(shè)為100,因?yàn)榕c嵌套的tableView.tag = 200要區(qū)分。
還要實(shí)現(xiàn)scrollView的代理方法,這個(gè)方法是實(shí)現(xiàn)滑動(dòng)的時(shí)候,不同的狀態(tài)改變。
#pragma mark - UIScrollerViewDelegate
//scrollview 的協(xié)議方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
float sub = _homeScrollView.contentOffset.x/WIDTH;
UIButton * btn = (UIButton * )[self.view viewWithTag:sub+100];
if ( _tempButton != btn) {
btn.selected = YES;
_tempButton.selected = NO;
_tempButton =btn;
}
}