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

(0)

相关推荐

  • iOS开发之使用Storyboard预览UI在不同屏幕上的运行效果

    在公司做项目一直使用Storyboard,虽然有时会遇到团队合作的Storyboard冲突问题,但是对于Storyboard开发效率之高还是比较划算的.在之前的博客中也提到过,团队合作使用Storyboard时,避免冲突有效的解决方法是负责UI开发的同事最好每人维护一个Storyboard, 公用的组件使用轻量级的xib或者纯代码来实现.这样不但提高了开发效率,而且可以有效的避免Storyboard的冲突.如果每个人维护一个Storyboard, 遇到冲突了就以你自己的为准就OK了. 言归正传,

  • 总结iOS App开发中控制屏幕旋转的几种方式

    在iOS6之前的版本中,通常使用 shouldAutorotateToInterfaceOrientation 来单独控制某个UIViewController的方向,需要哪个viewController支持旋转,只需要重写shouldAutorotateToInterfaceOrientation方法. 但是iOS 6里屏幕旋转改变了很多,之前的 shouldAutorotateToInterfaceOrientation 被列为 DEPRECATED 方法,查看UIViewController

  • iOS屏幕根据键盘自动变化高度

    一.效果图 二.代码 ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITextFieldDelegate> @end ViewController.m #import "ViewController.h" #define W [UIScreen mainScreen].bounds.size.width #define H [UISc

  • iOS开发中使用屏幕旋转功能的相关方法

    加速计是整个IOS屏幕旋转的基础,依赖加速计,设备才可以判断出当前的设备方向,IOS系统共定义了以下七种设备方向:   复制代码 代码如下: typedef NS_ENUM(NSInteger, UIDeviceOrientation) { UIDeviceOrientationUnknown, UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom UIDe

  • iOS开发中控制屏幕旋转的编写方法小结

    在iOS5.1 和 之前的版本中, 我们通常利用 shouldAutorotateToInterfaceOrientation: 来单独控制某个UIViewController的旋屏方向支持,比如: 复制代码 代码如下: - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  {      return (interfaceOrientation == UIInter

  • IOS开发中键盘输入屏幕上移的解决方法

    在IOS开法中经常会遇到键盘遮挡屏幕的事情(比如输入账号密码验证码等等),就使得原本都不大的屏幕直接占了一半甚至更多的位置,这倒无所谓,关键是挡住了下面的按钮.这样的话按钮的事件也就触发不了,最好的解决办法就是当输入这些信息的时候让整个屏幕上移一个键盘的位置,或者上移到指定的位置. 首先一般输入的话都用的是UITextField,所以要监听用户什么时候开始输入和什么时候结束输入,直接设置代理代理就行了,要遵受 UITextFieldDelegate协议. //遵循协议 @interface Vi

  • iOS中滑动控制屏幕亮度和系统音量(附加AVAudioPlayer基本用法和Masonry简单使用)

    如图,左侧上下滑动改变亮度,右侧上下滑动改变音量. 1.改变屏幕亮度 //获得当前屏幕亮度 light = [UIScreen mainScreen].brightness; light = 0.5f; //直接赋值或者使用set方法皆可 [UIScreen mainScreen].brightness = light; 2.改变系统音量 使用的比较多的就是通过MPMusicPlayerController来改变系统音量,主要归功于MPMusicPlayerController的音量和系统的同步

  • iOS应用开发中使用Auto Layout来适配不同屏幕尺寸

    简介 Auto Layout 是苹果在 Xcode 5 (iOS 6) 中新引入的布局方式,旨在解决 3.5 寸和 4 寸屏幕的适配问题.屏幕适配工作在 iPhone 6 及 plus 发布以后变得更加重要,而且以往的"笨办法"的工作量大幅增加,所以很多人开始学习使用 Auto Layout 技术. 初体验 0. 开发环境 本系列文章的开发环境为: OS X 10.10.3 Xcode Version 6.3.1 (6D1002) 1. 新建应用 新建一个 Single View Ap

  • iOS屏幕适配开发实用技巧

    一.旋转处理 第一步:注册通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFrames:) name:UIDeviceOrientationDidChangeNotification object:nil]; 第二步:处理接收事件 -(void)changeFrames:(NSNotification *)notification{ NSLog(@"change notifica

  • iOS如何获取屏幕宽高、设备型号、系统版本信息

    介绍 在我学习Android开发的时候,觉得设备适配是件很头疼的事情,android的设备太多了,那时就很羡慕iOS开发的人不用操心适配的问题,而当我开始学习iOS开发后,iOS的屏幕也开始多种多样了起来...于是也得做适配了,sad... 之前也研究过,这里把我的方法记录下来,本文介绍三个常用的设备信息获取方式: 获取屏幕的宽高.用于在设置控件位置的时候计算相对屏幕的距离 获取设备的型号.5s和6+的屏幕大小相差很远,相应的控件位置.大小都需要做出调整,不然就会出现在6+上显得很空旷或者在5s

随机推荐