IOS超級簡單上下左右滾動TableView,仿同花順自選列表
阿新 • • 發佈:2019-02-13
看到好多做的專案都用到左右滾動的tableView,以便放更多的行情資料內容,例如下圖這種:
現在把程式碼貼一下吧,反正思路也很簡單
核心程式碼很少,基本思路也很簡單,就是cell的聯動。
@implementation FMGodTableViewCell - (void)awakeFromNib { // Initialization code } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; } -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ if (self==[super initWithStyle:style reuseIdentifier:reuseIdentifier]) { [self createViews]; } return self; } -(void)createViews{ _mainView = [[UIScrollView alloc] initWithFrame:self.bounds]; _mainView.contentSize = CGSizeMake(4*_mainView.frame.size.width, 0); _mainView.delegate = self; _mainView.directionalLockEnabled = YES; [self.contentView addSubview:_mainView]; NSArray * strings = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"]; float w = _mainView.contentSize.width / strings.count; float x = 0; for (NSString *str in strings) { UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(x, 0, w, self.bounds.size.height)]; [_mainView addSubview:l]; l.text = str; l.textAlignment = NSTextAlignmentCenter; l = nil; x += w; } [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollMove:) name:GodCellScrollNotification object:nil]; } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ _isNotification = NO; } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ if (!_isNotification) { // 傳送通知 [[NSNotificationCenter defaultCenter] postNotificationName:GodCellScrollNotification object:self userInfo:@{@"x":@(scrollView.contentOffset.x)}]; } _isNotification = NO; } -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ // 避開自己發的通知,只有手指撥動才會是自己的滾動 if (!_isNotification) { // 傳送通知 [[NSNotificationCenter defaultCenter] postNotificationName:GodCellScrollNotification object:self userInfo:@{@"x":@(scrollView.contentOffset.x)}]; } NSArray *views = scrollView.subviews; UIView *first = views.firstObject; CGRect frame = first.frame; frame.origin.x = scrollView.contentOffset.x; first.frame = frame; _isNotification = NO; } -(void)scrollMove:(NSNotification*)notification{ NSDictionary *xn = notification.userInfo; NSObject *obj = notification.object; float x = [xn[@"x"] floatValue]; if (obj!=self) { _isNotification = YES; [_mainView setContentOffset:CGPointMake(x, 0) animated:NO]; }else{ _isNotification = NO; } obj = nil; }
Demo下載地址: https://github.com/dangfm/FMGodTableView
demo已用在成型的專案中:郵幣管家 App,案例可以檢視App Store,或者百度搜索 郵幣管家 專案下載地址:http://www.youbicard.com/templets/app/index.html
交流QQ群: 368295440