iOS 中根据屏幕宽度自适应分布按钮的实例代码
程序员文章站
2023-12-19 23:16:10
下载demo链接:https://github.com/minlee6/buttonshow.git
屏幕摆放的控件有两种方式,一种根据具体内容变化,一种根据...
下载demo链接:https://github.com/minlee6/buttonshow.git
屏幕摆放的控件有两种方式,一种根据具体内容变化,一种根据屏幕宽度变化。
下面我分别将两个方式,用代码的方式呈现:
1:根据具体内容变化
// // styleoneviewcontroller.m // buttonshow // // created by limin on 15/06/15. // copyright © 2015年 信诺汇通信息科技(北京)有限公司. all rights reserved. // #import "styleoneviewcontroller.h" #import "uiviewext.h" //每列间隔 #define kviewmargin 10 //每行列数高 #define kvieh 28 #define kscreenw [uiscreen mainscreen].bounds.size.width #define color(r,g,b) [uicolor colorwithred:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0] @interface styleoneviewcontroller () { uibutton *tmpbtn; cgfloat btnw; cgfloat btnviewheight; } /* 存放按钮的view */ @property(nonatomic,strong)uiview *btnsview; /* 按钮上的文字 */ @property(nonatomic,strong)nsmutablearray *btnmsgarrays; @property (nonatomic,strong) nsmutablearray* btnidarrays; /** 所有按钮 */ @property(nonatomic,strong)nsmutablearray *allbtnarrays; /** 服务器提供按钮标签 */ @property(nonatomic,strong)nsarray *taginfoarray; //-------展示选中的文字 /* 确认按钮 */ @property(nonatomic,strong)uibutton *surebutton; /* 文字 */ @property(nonatomic,strong)uilabel *showlabel; @end @implementation styleoneviewcontroller - (void)viewdidload { [super viewdidload]; self.view.backgroundcolor = [uicolor whitecolor]; [self gettagmsg]; } -(void)gettagmsg { self.btnmsgarrays = [[nsmutablearray alloc]init]; _allbtnarrays = [[nsmutablearray alloc]init]; self.btnidarrays = [[nsmutablearray alloc]init]; self.taginfoarray = @[@{@"id":@"1",@"tagmsg":@"味道很好味道很好"}, @{@"id":@"1",@"tagmsg":@"环境不错"}, @{@"id":@"1",@"tagmsg":@"性价比高"}, @{@"id":@"1",@"tagmsg":@"位置好找"}, @{@"id":@"1",@"tagmsg":@"上菜快"}, @{@"id":@"1",@"tagmsg":@"菜量足"}, @{@"id":@"1",@"tagmsg":@"好吃"}, @{@"id":@"1",@"tagmsg":@"态度好,服务周到"} ]; //挨个赋值 for (int i=0; i<_taginfoarray.count; i++) { nsdictionary *dict = _taginfoarray[i]; [self.btnidarrays addobject:dict[@"id"]]; [self.btnmsgarrays addobject:dict[@"tagmsg"]]; } [self createbtns]; } //创建按钮 -(void)createbtns{ //创建放置button的view self.btnsview = [[uiview alloc]initwithframe:cgrectmake(10, 40, kscreenw-2*kviewmargin, 40)]; self.btnsview.backgroundcolor = color(237, 237, 237); [self.view addsubview:self.btnsview]; /** * 数组存放适配屏幕大小的每行按钮的个数 */ nsmutablearray *indexbtns=[self returnbtnsforrowandcol]; //统计按钮view的高度 btnviewheight=indexbtns.count*(kvieh+kviewmargin)+10; //设置btnview的高度 self.btnsview.height=btnviewheight; nsinteger count=0; cgfloat y; //循环创建按钮 for (int row=0; row<indexbtns.count; row++) { for (int col=0; col<[indexbtns[row]intvalue]; col++) { cgfloat x; y=10+row*(kviewmargin+kvieh); //按钮的宽 btnw=[self returnbtnwithwithstr:self.btnmsgarrays[count]]; if (tmpbtn&&col) { x=cgrectgetmaxx(tmpbtn.frame)+kviewmargin; }else{ x=kviewmargin+col*btnw; } uibutton *btn=[[uibutton alloc]initwithframe:cgrectmake(x, y, btnw, kvieh)]; [btn settitle:self.btnmsgarrays[count] forstate:uicontrolstatenormal]; btn.titlelabel.font=[uifont systemfontofsize:12]; btn.layer.borderwidth=1; btn.layer.bordercolor = color(156,156,156).cgcolor; [btn settitlecolor:color(156, 156, 156) forstate:uicontrolstatenormal]; [btn settitlecolor:color(202, 48, 130) forstate:uicontrolstateselected]; btn.backgroundcolor=[uicolor clearcolor]; btn.layer.cornerradius=2; btn.tag=[self.btnidarrays[count] integervalue]; [btn addtarget:self action:@selector(btnclick:) forcontrolevents:uicontroleventtouchupinside]; [self.allbtnarrays addobject:btn]; tmpbtn=btn; [self.btnsview addsubview:btn]; count+=1; } } //创建确认按钮 uibutton *btn = [[uibutton alloc]initwithframe:cgrectmake(kviewmargin, self.btnsview.bottom+40, kscreenw-2*kviewmargin, 44)]; [btn settitle:@"确认" forstate:uicontrolstatenormal]; [btn settitlecolor:[uicolor whitecolor] forstate:uicontrolstatenormal]; btn.backgroundcolor = color(214, 116, 0); [btn addtarget:self action:@selector(showselectedclick:) forcontrolevents:uicontroleventtouchupinside]; self.surebutton = btn; [self.view addsubview:btn]; //返回按钮 uibutton *btn2 = [[uibutton alloc]initwithframe:cgrectmake((kscreenw-80)*0.5, self.view.height-80, 80, 80)]; [btn2 settitle:@"返回" forstate:uicontrolstatenormal]; [btn2 settitlecolor:[uicolor purplecolor] forstate:uicontrolstatenormal]; btn2.layer.cornerradius = 40; btn2.clipstobounds = yes; btn2.layer.bordercolor = [uicolor purplecolor].cgcolor; btn2.layer.borderwidth = 2; [btn2 addtarget:self action:@selector(backbtnclick:) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:btn2]; } #pragma mark-返回view中有几行几列按钮 -(nsmutablearray*)returnbtnsforrowandcol{ cgfloat allwidth = 0.0; nsinteger countw=0; nsmutablearray *indexbtns=[nsmutablearray array]; nsmutablearray *tmpbtns=[nsmutablearray array]; for (int j=0;j<self.btnmsgarrays.count;j++) { cgfloat width=[self returnbtnwithwithstr:self.btnmsgarrays[j]]; allwidth+=width+kviewmargin; countw+=1; if (allwidth>kscreenw-10) { //判断第一行情况 nsinteger lastnum=[[tmpbtns lastobject]integervalue]; [indexbtns addobject:@(lastnum)]; [tmpbtns removeallobjects]; allwidth=0.0; countw=0; j-=1; }else{ [tmpbtns addobject:@(countw)]; } } if (tmpbtns.count!=0) { nsinteger lastnum=[[tmpbtns lastobject]integervalue]; [indexbtns addobject:@(lastnum)]; } return indexbtns; } -(cgfloat)returnbtnwithwithstr:(nsstring *)str{ //计算字符长度 nsdictionary *minattributesri = @{nsfontattributename:[uifont systemfontofsize:12]}; cgsize mindetailsizeri = [str boundingrectwithsize:cgsizemake(100, maxfloat) options:nsstringdrawingusesfontleading attributes:minattributesri context:nil].size; return mindetailsizeri.width+12; } #pragma mark-按钮点击事件 -(void)btnclick:(uibutton *)btn { btn.selected = !btn.isselected; if (btn.isselected) { btn.layer.bordercolor = color(202, 48, 130).cgcolor; }else { btn.layer.bordercolor = color(156, 156, 156).cgcolor; } } -(void)showselectedclick:(uibutton *)btn { nsmutablearray *strarray = [[nsmutablearray alloc]init]; for (uibutton *btn in self.allbtnarrays) { if (btn.isselected) { [strarray addobject:btn.currenttitle]; } } nsstring *str = [strarray componentsjoinedbystring:@" & "]; uifont *font = [uifont systemfontofsize:14]; cgfloat strh = [str boundingrectwithsize:cgsizemake(kscreenw-2*kviewmargin, maxfloat) options:nsstringdrawinguseslinefragmentorigin attributes:@{nsfontattributename:font} context:nil].size.height; //展示文字 if (!self.showlabel) { uilabel *label = [[uilabel alloc]initwithframe:cgrectmake(kviewmargin, self.surebutton.bottom+20, kscreenw-2*kviewmargin, strh)]; label.font = font; label.textcolor = [uicolor redcolor]; label.numberoflines = 0; self.showlabel = label; [self.view addsubview:label]; } self.showlabel.text = str; self.showlabel.height = strh; } -(void)backbtnclick:(uibutton *)btn { [self dismissviewcontrolleranimated:yes completion:nil]; } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of any resources that can be recreated. } /* #pragma mark - navigation // in a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { // get the new view controller using [segue destinationviewcontroller]. // pass the selected object to the new view controller. } */ @end
2:根据屏幕宽度变化。
//// styletwoviewcontroller.m // buttonshow // // created by limin on 16/11/15. // copyright © 2016年 君安信(北京)科技有限公司. all rights reserved. // #import "styletwoviewcontroller.h" #import "uiviewext.h" #define ktagmargin 14 #define kcellmargin 15 #define kscreenwidth [uiscreen mainscreen].bounds.size.width #define color(r,g,b) [uicolor colorwithred:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0] @interface styletwoviewcontroller () /* 按钮 */ @property(nonatomic,strong)nsmutablearray *btnsarray; /* 按钮文字 */ @property(nonatomic,strong)nsarray *tagsarray; /* 默认选择的按钮 */ @property(nonatomic,strong)uibutton *selectedbtn; /* 标签 */ @property(nonatomic,copy)nsstring *selecttopictitle; @end @implementation styletwoviewcontroller - (void)viewdidload { [super viewdidload]; self.view.backgroundcolor = [uicolor whitecolor]; [self gettagmsg]; } -(void)gettagmsg { _btnsarray = [nsmutablearray array]; //添加tag按钮 nsarray *tagsarray = @[@"美好生活1",@"美好生活2",@"美好生活3",@"美好生活4",@"美好生活5",@"美好生活6",@"美好生活7",@"美好生活8",@"美好生活9",@"美好生活10",@"美好生活11",@"美好生活12",@"美好生活13",@"美好生活14",@"美好生活15",@"美好生活16",@"美好生活17",@"美好生活18",@"美好生活19",@"美好生活20",@"美好生活21",@"美好生活22",@"美好生活23",@"美好生活24"]; _tagsarray = tagsarray; [self createtagsqures:tagsarray]; } #pragma mark - 创建方块 -(void)createtagsqures:(nsarray *)tags { //一行最多4个。 int maxcols = 4; //宽度、高度 cgfloat totalwidth = kscreenwidth - 2*kcellmargin - (maxcols-1)*ktagmargin; cgfloat btnwidth = totalwidth / maxcols; cgfloat btnheight = 30; for (int i=0; i<tags.count; i++) { //创建按钮 uibutton *btn = [uibutton buttonwithtype:uibuttontypecustom]; btn.backgroundcolor = color(211, 156, 4); //设置按钮属性 [btn setbackgroundimage:[uiimage imagenamed:@"discover_btnbg"] forstate:uicontrolstatenormal]; [btn setbackgroundimage:[uiimage imagenamed:@"discover_btnbg"] forstate:uicontrolstatedisabled]; btn.adjustsimagewhenhighlighted = no; [btn settitlecolor:color(51, 51, 51) forstate:uicontrolstatenormal]; [btn settitlecolor:[uicolor whitecolor] forstate:uicontrolstatedisabled]; [btn.titlelabel setfont:[uifont systemfontofsize:13]]; btn.titlelabel.textalignment = nstextalignmentcenter; btn.tag = i+10; // 监听点击 [btn addtarget:self action:@selector(tagbtnclick:) forcontrolevents:uicontroleventtouchupinside]; //按钮赋值 [btn settitle:tags[i] forstate:uicontrolstatenormal]; [self.view addsubview:btn]; //计算frame int col = i % maxcols; int row = i / maxcols; btn.x = kcellmargin + col*(btnwidth + ktagmargin); btn.y = 40 + 11 + row * (btnheight + ktagmargin); btn.width = btnwidth; btn.height = btnheight; //设置所有按钮默认状态为no 。 btn.enabled = yes; [self.btnsarray addobject:btn]; } //默认第一个按钮为选中 uibutton *btn = self.btnsarray[0]; btn.enabled = no; self.selectedbtn = btn; self.selecttopictitle = self.tagsarray[0]; //返回按钮 uibutton *btn2 = [[uibutton alloc]initwithframe:cgrectmake((kscreenwidth-80)*0.5, self.view.height-160, 80, 80)]; [btn2 settitle:@"返回" forstate:uicontrolstatenormal]; [btn2 settitlecolor:[uicolor purplecolor] forstate:uicontrolstatenormal]; btn2.layer.cornerradius = 40; btn2.clipstobounds = yes; btn2.layer.bordercolor = [uicolor purplecolor].cgcolor; btn2.layer.borderwidth = 2; [btn2 addtarget:self action:@selector(backbtnclick:) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:btn2]; //创建确认按钮 uibutton *btn3 = [[uibutton alloc]initwithframe:cgrectmake(kcellmargin, btn2.top-80, kscreenwidth-2*kcellmargin, 44)]; [btn3 settitle:@"确认" forstate:uicontrolstatenormal]; [btn3 settitlecolor:[uicolor whitecolor] forstate:uicontrolstatenormal]; btn3.backgroundcolor = color(214, 116, 0); [btn3 addtarget:self action:@selector(showselectedclick:) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:btn3]; } #pragma mark - 按钮点击事件 - (void)tagbtnclick:(uibutton *)button { //获取点击的button,取消选中样式 self.selectedbtn.enabled = yes; button.enabled = no; self.selectedbtn = button; nsinteger index = button.tag-10; nsstring *selectstr = self.tagsarray[index]; self.selecttopictitle = selectstr; } -(void)showselectedclick:(uibutton *)button { //保留选择标签的文字 nslog(@"所选择的文字:%@",self.selecttopictitle); uialertview *alert = [[uialertview alloc]initwithtitle:self.selecttopictitle message:@"" delegate:nil cancelbuttontitle:@"确认" otherbuttontitles:nil]; [alert show]; } -(void)backbtnclick:(uibutton *)btn { [self dismissviewcontrolleranimated:yes completion:nil]; } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of any resources that can be recreated. } /* #pragma mark - navigation // in a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { // get the new view controller using [segue destinationviewcontroller]. // pass the selected object to the new view controller. } */ @end
以上所述是小编给大家介绍的ios 中根据屏幕宽度自适应分布按钮的实例代码,希望对大家有所帮助