iOS--九宫格布局
Posted 其意亦凡
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS--九宫格布局相关的知识,希望对你有一定的参考价值。
[self rankWithTotalColumns:2 andWithAppW:180 andWithAppH:170]; //九宫格布局 - (void)rankWithTotalColumns:(int)totalColumns andWithAppW:(int)appW andWithAppH:(int)appH{ //总列数 int _totalColumns = totalColumns; //view尺寸 CGFloat _appW = appW; CGFloat _appH = appH; //横向间隙 (控制器view的宽度 - 列数*应用宽度)/(列数 + 1) CGFloat margin = (self.view.frame.size.width - (_totalColumns * 180)) / (_totalColumns + 1); NSLog(@"%lu",(unsigned long)self.TitleList.count); for (int index = 0; index < self.TitleList.count; index++) { //创建一个小框框// UIView *appView = [[UIView alloc] init]; appView.backgroundColor = [UIColor whiteColor]; appView.layer.borderColor = [[UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1] CGColor]; appView.layer.borderWidth = 1; DataOldBody *item =[self.TitleList objectAtIndex:index]; // 添加图片 UIButton *iconView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 180, 120)]; UIImage *normal = [UIImage imageNamed:item.CharPicName]; [iconView setBackgroundImage:normal forState:UIControlStateNormal]; //添加点击事件 [iconView addTarget:self action:@selector(handTap:) forControlEvents:UIControlEventTouchUpInside]; [iconView setTag:item.CharId]; [appView addSubview:iconView]; //添加简介信息 UILabel *label = [[UILabel alloc] init]; label.text = item.CharBodyText; label.frame = CGRectMake(0, 123, 180, 45); label.font = [UIFont fontWithName:@"Kailasa" size:13]; label.textAlignment = NSTextAlignmentCenter; label.numberOfLines = 2; [appView addSubview:label]; if (moonAndSuns) { label.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1]; label.textColor = [UIColor whiteColor]; }else{ label.backgroundColor = [UIColor whiteColor]; label.textColor = [UIColor blackColor]; } //创建结束// //计算框框的位置...行号列号从0开始 //行号 int row = index / totalColumns; //行号为框框的序号对列数取商 //列号 int col = index % totalColumns; //列号为框框的序号对列数取余 CGFloat appX = margin + col * (appW + margin); // 每个框框靠左边的宽度为 (平均间隔+框框自己的宽度) CGFloat appY = 20 + row * (appH + margin); // 每个框框靠上面的高度为 平均间隔+框框自己的高度 appView.frame = CGRectMake(appX, appY, _appW, _appH); [self.scrollView addSubview:appView]; } } -(void)handTap:(id)sender{ NSInteger i = [sender tag]; NSLog(@"%ld",(long)i); OldFirstBodyViewController *OldFirstBody = [self.storyboard instantiateViewControllerWithIdentifier:@"OldFirstBody"]; OldFirstBody.index = i; [self.navigationController pushViewController:OldFirstBody animated:YES]; }
以上是关于iOS--九宫格布局的主要内容,如果未能解决你的问题,请参考以下文章