iOS 中根据屏幕宽度自适应分布按钮的实例代码_IOS

 下载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 中根据屏幕宽度自适应分布按钮的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索ios
按钮自适应宽度
ios 按钮自适应宽度、按钮自适应宽度、css 宽度自适应、div 宽度自适应、input 宽度自适应,以便于您获取更多的相关知识。

时间: 2024-09-15 00:33:55

iOS 中根据屏幕宽度自适应分布按钮的实例代码_IOS的相关文章

JavaScript中实现无缝滚动、分享到侧边栏实例代码_javascript技巧

废话不多说,直接给大家贴代码了,代码解决一起问题! 下面一段代码给大家介绍js无缝滚动实例代码: 代码如下所示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml&

java的Map集合中按value值进行排序输出的实例代码_java

java的Map集合中按value值进行排序输出的实例代码 import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; public class Test { public static void main(String[] args) { Map<String ,Integer> map = new Has

Android实现空心圆角矩形按钮的实例代码

页面上有时会用到背景为空心圆角矩形的Button,可以通过xml绘制出来. drawrable文件夹下bg_red_hollow_rectangle.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle&qu

Android中ActionBar和ToolBar添加返回箭头的实例代码

1.ActionBar添加返回箭头 //onCreate方法中 ActionBar actionBar = this.getSupportActionBar(); actionBar.setTitle("搜索功能"); actionBar.setDisplayHomeAsUpEnabled(true); //activity类中的方法 @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getI

iOS App中UIPickerView选择栏控件的使用实例解析_IOS

UIPickerView控件是比UIDatePicker控件更普通的Picker控件,UIDatePicker控件可以理解成是从UIPickerView控件加工出来的专门进行日期选择的控件. UIPickerView控件的用法比UIDatePicker复杂一点.本文中的小例子将用UIPickerView控件做出两种效果,第一个只有一个转盘,第二个有两个转盘,但这两个转盘之间没有依赖关系,也就是说改变其中一个转盘中的选择,不会对第二个转盘产生影响.在下一篇文章会做一个转盘之间有依赖关系的例子. 下

iOS中关于信鸽推送的使用demo详解_IOS

最近在看推送方面的知识,用的是信鸽推送主要是因为后台用的是信鸽 推送用第三方推送,也就是在客户端建一个广播接收器,当服务器发送消息时发送到信鸽,信鸽再发送一次,广播接受器接受下: 我实现的功能比较简单,当app在运行状态时,会在主页展示一个弹窗展示推送的消息:如果app不在运行状态且service没被销毁就展示默认的通知 那么如何在主页展示弹窗:当广播接受器收到我要的消息时,用观察者模式,收到消息在发送个消息个主界面 官方的Demo连接:http://xg.qq.com/xg/help/ctr_

iOS中 LGLAlertView 提示框的实例代码_IOS

使用与iOS8 以后,只是把系统的UIAlertController进行了封装,省的每次用的时候要写很多的代码.封装后只需要一句代码即可 , deome 地址 :https://github.com/liguoliangiOS/LGLAlertView.git 上代码LGLAlertView.h: #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> typedef NS_ENUM(NSInteger, LGLAlert

IOS中获取本地通讯录联系人以及汉字首字母排序_IOS

iOS中获取手机通讯录中的联系人信息: /*** 加载本地联系人*/ - (void)loadLocalContacts { //新建一个通讯录类 ABAddressBookRef addressBooks = nil; if (DeviceVersion < 6.0) { addressBooks = ABAddressBookCreate(); } else { addressBooks = ABAddressBookCreateWithOptions(NULL, NULL); //获取通讯

iOS中nil、Nil、NULL、NSNull详解_IOS

ObjC 里面的几个空值符号经常会差点把我搞死,这些基础的东西一点要弄清楚才行,以提高码农的基本素质. nil nil 是 ObjC 对象的字面空值,对应 id 类型的对象,或者使用 @interface 声明的 ObjC 对象. 例如: NSString *someString = nil; NSURL *someURL = nil; id someObject = nil; if (anotherObject == nil) // do something 定义: // objc.h #if