自定义颜色
UIColor *color = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
Label自定义高度
//先设定label的行数为0
label.numberOfLines = 0;
//动态计算上述文字所需要的宽高
CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(200, 1000)];
label.frame = CGRectMake(0, 20, size.width, size.height);
Label倒角
label.layer.cornerRadius = 50;
alpha为 0(全透明) 1———0 透明度上升
图标变圆
UIImageView *img = nil;
img.layer.cornerRadius = 25.0f;
img.clipsToBounds = YES;
APP更改名字
在InfoPlist.strings 写上 CFBundleDisplayName="霸气的第一次";
APP更改图标
图片名字为
Icon.png 或者 [email protected]
制作两个按钮(只能单选)
//1.加载图片
//除png不需要后缀外,其余格式图片一律需要添加后缀
UIImage *unchecked = [UIImage imageNamed:@"unchecked"];
UIImage *checked = [UIImage imageNamed:@"checked"];
UIImage *normal = [UIImage imageNamed:@"3_normal"];
UIImage *selected = [UIImage imageNamed:@"3_selected"];
//2.创建按钮
btn = [UIButton buttonWithType:UIButtonTypeCustom];
heart = [UIButton buttonWithType:UIButtonTypeCustom];
//按下去没有高亮的效果
btn.adjustsImageWhenHighlighted = NO;
//3.设置按钮图片
[btn setImage:unchecked forState:UIControlStateNormal];
[btn setImage:checked forState:UIControlStateSelected];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake(30, 30, unchecked.size.width, unchecked.size.height);
[self.window addSubview:btn];
heart.adjustsImageWhenHighlighted = NO;
[heart setImage:normal forState:UIControlStateNormal];
[heart setImage:selected forState:UIControlStateSelected];
[heart addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
heart.frame = CGRectMake(150, 30, normal.size.width, normal.size.height);
heart.backgroundColor = [UIColor redColor];
[self.window addSubview:heart];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)btnClick:(UIButton *)sender
{
//实现单选
//1.将所有按钮的selected状态改为NO
btn.selected = NO;
heart.selected = NO;
sender.selected = !sender.isSelected;
}
山寨微信(各种触发事件)
_label = [[UILabel alloc] init];
_label.frame = CGRectMake(50, 50, 200, 200);
_label.backgroundColor = [UIColor cyanColor];
[self.window addSubview:_label];
UIControl *control = [[UIControl alloc] init];
control.frame = CGRectMake(10, 480 - 50, 300, 50);
control.backgroundColor = [UIColor greenColor];
//按一下
[control addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
//按住放开
[control addTarget:self action:@selector(touchUpInside) forControlEvents:UIControlEventTouchUpInside];
//按住拖到外面
[control addTarget:self action:@selector(touchDragExit) forControlEvents:UIControlEventTouchDragExit];
//按住拖到里面
[control addTarget:self action:@selector(touchDragEnter) forControlEvents:UIControlEventTouchDragEnter];
//按住在外面放开
[control addTarget:self action:@selector(touchUpOutSide) forControlEvents:UIControlEventTouchUpOutside];
[self.window addSubview:control];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)touchUpOutSide
{
_label.text = @"已取消";
}
- (void)touchDragExit
{
_label.text = @"松开取消";
}
- (void)touchDragEnter
{
_label.text = @"松开发送";
}
- (void)touchUpInside
{
_label.text = @"发送成功";
}
- (void)touchDown
{
_label.text = @"松开发送";
}
imageView的适配
//拉伸图片,填满整个view,但是图片有可能会变形
//UIViewContentModeScaleToFill
//等比例拉伸内容,只要宽或者高触顶,停止拉伸
//UIViewContentModeScaleAspectFit
//等比例拉伸内容,直到全部填满,此时内容就有可能超过view的大小
//如果不需要超出部分,则可以使用clipsToBonuds进行裁剪
//UIViewContentModeScaleAspectFill
imageView.contentMode = UIViewContentModeScaleToFill;
imageView.backgroundColor = [UIColor redColor];
imageView.frame = CGRectMake(100, 100, 100, 100);
imageView.clipsToBounds = YES;
汤姆猫(动画)
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(0, 0, 320, 480);
//1.准备电影胶卷
NSMutableArray *films = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i <= 80; ++i)
{
//cat_drink0000.jpg
NSString *name = [NSString stringWithFormat:@"cat_drink%04d.jpg", i];
UIImage *image = [UIImage imageNamed:name];
[films addObject:image];
}
imageView.image = films[0];
//2.将胶卷装到imageView中
imageView.animationImages = films;
//3.设置播放总时间
imageView.animationDuration = 5.f;
//4.设置重复次数,0为无限循环
imageView.animationRepeatCount = 0;
//5.开始播放
[imageView startAnimating];
//6.结束播放
//[imageView stopAnimating];
//7.判断当前播放状态
//[imageView isAnimating];
UITapGestureRecognizer(手势三部曲)
//1、创建手势
UITapGestureRecognizer *r1 = [[UITapGestureRecognizer alloc] init];
//2、手势触发事件
[r1 addTarget:self action:<#(SEL)#>];
//3、把手势应用在哪
[self.window addGestureRecognizer:r1];
启动动画
[UIView animateWithDuration:<#(NSTimeInterval)#> animations:<#^(void)animations#> completion:<#^(BOOL finished)completion#>]
tranform 的运用
CGAffineTransform old = imagev.transform;
//旋转
imagev.transform = CGAffineTransformRotate(old, M_PI_2);
/ /平移
imagev.transform = CGAffineTransformTranslate(old, 100, 0);
//缩放
imagev.transform = CGAffineTransformScale(old, 1.5, 1.5);
结构体转化成字符串
CGRect bounds:(0, 0, weight, height);
CGPoint center;(x, y);
NSLog(@"bounds = %@", NSStringFromCGRect(bounds));
NSLog(@"center = %@", NSStringFromCGPoint(center));
uiviewcontrol
1.uiviewcontrol的切换
//1.实例化要切换的控制器对象
QFViewController2 *green = [[QFViewController2 alloc] init];
//2.设置切换动画
green.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//3.利用ViewController中的方法进行切换
//模态视图
[self presentViewController:green animated:YES completion:nil];
//1 回到之前的页面
[self dismissViewControllerAnimated:YES completion:nil];
2.uiviewcontrol的正向传值:viewcontrol1 —> viewcontrol2
viewcontrol1:
- (void)nextVc
{
//1.实例化要切换的控制器对象
QFViewController2 *green = [[QFViewController2 alloc] init];
//设置要传递给green控制器的内容
//可以通过setter传递,也可以通过单独写一个方法进行传递
green.username = @"1000phone";
green.password = @"123456";
//设置切换动画
green.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//2.利用ViewController中的方法进行切换
//模态视图
[self presentViewController:green animated:YES completion:nil];
modalTransitionStyle
UIModalTransitionStyleCoverVertical 从下向上√
UIModalTransitionStyleCrossDissolve 渐变
UIModalTransitionStyleFlipHorizontal 横向翻转
UIModalTransitionStylePartialCurl 翻书
}
viewcontrol2:
@interface QFViewController2 : UIViewController
@property (nonatomic, strong) NSString *username;
@property (nonatomic, strong) NSString *password;
@end
定义全局变量,用来保存从uiviewcontrol1传来的数据!
3.利用中间对象传值(把值保存到delegate)
//如果是容器,要在所有的viewcontroller之前进行实例化
在这里WLDAppDelegate.m弄
self.arr = [[NSMutableArray alloc] init];
viewcontrol1:
//当前应用程序的对象
UIApplication *app = [UIApplication sharedApplication];
//获取当前app的代理对象
WLDAppDelegate *delegate = app.delegate;
delegate.passWord = @"hsdkjfhkasf";
- (void)next
{
WLDViewController2 *c2 = [[WLDViewController2 alloc] init];
c2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:c2 animated:YES completion:nil];
}
viewcontrol2:
UIApplication *app = [UIApplication sharedApplication];
WLDAppDelegate *delegate = app.delegate;
NSLog(@"%@", delegate.passWord);
- (void)per
{
[self dismissViewControllerAnimated:YES completion:nil];
}
4.反向传值时需要运用到代理(viewcontrol2 -> viewcontrol1)
//QFViewController2 委托 QFViewController1 接收处理好的数据
// 被代理 代理
//定义代理协议
//让代理对象遵循协议
//在被代理对象中声明一个代理对象成员
textfield
//设置textfield
UITextField *f1 = [[UITextField alloc] init];
f1.frame = CGRectMake(10, 50, 300, 40);
//设置边框 ()
f1.borderStyle = UITextBorderStyleRoundedRect;
//设置键盘类型
//textField.keyboardType = UIKeyboardTypeNumberPad;
//设置提示信息
f1.placeholder = @"请输入密码";
//设置密文输入
f1.secureTextEntry = YES;
//设置一键清除按钮
f1.clearButtonMode = UITextFieldViewModeWhileEditing;
//设置字体高度
f1.adjustsFontSizeToFitWidth = YES;
//设置return 按钮类型
f1.returnKeyType = UIReturnKeyEmergencyCall;
[self.view addSubview:f1];
//禁止用键盘
textField.enabled = NO;
隐藏键盘textfield
(点击返回return键或者点击空白处)
1.首先遵守协议:(textfielddelegate)
2.设置代理: self.delegate = self
3.
//通过设置代理来点击return键隐藏键盘
f1.delegate = self;
//点击空白出就隐藏键盘
UITapGestureRecognizer *t1 = [[UITapGestureRecognizer alloc] init];
[t1 addTarget:self action:@selector(hide)];
[self.view addGestureRecognizer:t1];
}
- (void)hide
{
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
键盘遮挡
//通过通知中心获取键盘的升起和隐藏状态
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//1.谁去处理
//2.如何处理
//3.监听键盘的升起和落下
[center addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[center addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//得有协议
textField.delegate = self;
//1 通过协议,获得正在编辑的文本框
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
/*获取当前正在编辑的文本框*/
_texf = textField;
}
//2 键盘升起时,view的抬起
- (void)keyBoardWillShow:(NSNotification *)sender
{
NSLog(@"%@", sender);
//包含了键盘的所有信息
NSDictionary *userInfo = sender.userInfo;
//结束时键盘的fram状态
NSValue *frameValue = userInfo[@"UIKeyboardFrameEndUserInfoKey"];
NSNumber *timeValue = userInfo[@"UIKeyboardAnimationDurationUserInfoKey"];
//将NSValue --> CGRect
//1.准备一个空的CGRect
CGRect keyBoardFrame;
//2.从NSValue中去获取
[frameValue getValue:&keyBoardFrame];
NSLog(@"%@+++", NSStringFromCGRect(keyBoardFrame));
/*判断是否被键盘遮蔽*/
if (CGRectGetMaxY(_texf.frame) > CGRectGetMinY(keyBoardFrame))
{
CGRect oldFrame = self.view.frame;
/***重新计算要上移的偏移量***/
CGFloat newY = 480 - CGRectGetHeight(keyBoardFrame) - CGRectGetMaxY(_texf.frame);
CGRect newFrame = CGRectMake(0, newY, CGRectGetWidth(oldFrame), CGRectGetHeight(oldFrame));
[UIView animateWithDuration:[timeValue floatValue] animations:^{
self.view.frame = newFrame;
}];
}
//3 键盘消失时,view的落下
- (void)keyBoardWillHide:(NSNotification *)sender
{
[UIView animateWithDuration:0.25 animations:^{
self.view.frame = CGRectMake(0, 0, 320, 480);
}];
}
UINavigationController
1 初始化导航控制器
ViewController1 *root = [[ViewController1 alloc] init];
//初始化导航控制器,把导航控制器加载到v1中
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:root];
self.window.rootViewController = navi;
2 定制自己viewcontrol的导航控制器
1 定制导航控制器标题
self.navigationItem.title = @"dsfs";
2 定制导航控制器的左右按钮
[1]利用系统自带的按钮
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
self.navigationItem.leftBarButtonItem = item;
系统自带的按钮:
[2]把按钮改成文字
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:nil action:nil];
UIImage *image = [UIImage imageNamed:@"refresh_30"];
[3]把按钮改成自带的图片
UIBarButtonItem *rightItemImage = [[UIBarButtonItem alloc] initWithImage:i[UIImage imageNamed:@"refresh_30"] style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightItemImage;
3 定制导航控制器的titleView,把按钮添加到titleView上
btn 为一个按钮
self.navigationItem.titleView = btn;
4 定制下一个viewControl的返回按钮,我们应该在前一个viewControl就写代码:
如果我们没写默认为back按钮
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"aaa" style:UIBarButtonItemStylePlain target:nil action:nil];
5 如果leftBarButtonItem存在,则会自动隐藏backBarButtonItem
//设置以下属性为YES则可以让两者共存
self.navigationItem.leftItemsSupplementBackButton = YES;
6 如果我们想隐藏back按钮(应该很少用这个)
self.navigationItem.hidesBackButton = YES;
===============================================
导航控制器
1.
WLDViewController1 *red = [[WLDViewController1 alloc] init];
//实例化导航控制器
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:red];
self.window.rootViewController = navi;
2. //导航条设置透明,ios7默认透明,7以前为不透明
默认:
更改导航条的透明属性(变为不透明)navi.navigationBar.translucent = NO;
更改导航条的背景图片(设置导航条背景图片,导航则会变为不透明)
如果导航条为不透明的,添加背景图片,
navi.navigationBar.translucent = NO;
//更改导航条的背景 图片 问!
UIImage *image = [UIImage imageNamed:@"bar"];
[navi.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
效果:(导航条颜色更深)
如果导航条为透明的,添加背景图片,
navi.navigationBar.translucent = YES;
//更改导航条的背景 图片 问!
UIImage *image = [UIImage imageNamed:@"bar"];
[navi.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
效果:
在QFRedViewController上加控件
//如果导航条透明,起始坐标为(0,64)
//如果导航条不透明,起始坐标为(0,0)
我们IOS6以上就是透明的了!
以IOS7为例子
UIView *v = [[UIView alloc] init];
v.frame = CGRectMake(0, 0, 100, 100);
v.backgroundColor = [UIColor blackColor];
[self.view addSubview:v];
效果:
定制导航栏内容:(重点)都在自己的control上搞
1.添加导航栏的中间内容
在control的init方法里面添加内容
//定制导航条内容
self.title = @"superman";
2.//添加导航上的左按钮
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(leftPress)];
//导航控制器会加载每个viewcontroller中的navigationitem,并且将该对象的内容添加到导航条之上
self.navigationItem.leftBarButtonItem = leftItem;
2 自定义添加导航上的按钮(右边)—文字
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightItem;
2 自定义添加导航栏上的按钮(右边)— 图片
UIImage *image = [UIImage imageNamed:@"refresh_30"];
UIBarButtonItem *rightItemImage = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightItemImage;
3.按导航上按钮进入下一个control
首先利用按钮的方法
self.navigationItem.leftBarButtonItem = leftItem;
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(next)];
self.navigationItem.rightBarButtonItem = rightItem;
方法是:
- (void)next
{
QFBlueViewController *blue = [[QFBlueViewController alloc] init];
//获取到当前所在的导航控制器
[self.navigationController pushViewController:blue animated:YES];
}
切换到这个control:
在导航上添加按钮返回到上一个control
if (self) {
// Custom initialization
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"回去" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
self.navigationItem.rightBarButtonItem = rightItem;
}
return self;
}
- (void)back
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
切换到上一个
3. 把返回键按钮改了
//在当前页面设置返回按钮,会在下一个页面出现
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"xxxx" style:UIBarButtonItemStylePlain target:nil action:nil];
改成xxxx
//如果leftBarButtonItem(如果左边按钮存在)存在,则会自动隐藏backBarButtonItem(就是上面那个xxxx)
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"refresh_30"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
self.navigationItem.leftBarButtonItem = back;
方法为:
- (void)back
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
但如果加上 //隐藏back按钮
self.navigationItem.hidesBackButton = YES;
则两个按钮共存
===============================================
添加左边(右边按钮),按钮要自定义图片则需要以下方法
1)首先要设置按钮,图片放在按钮上
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame = CGRectMake(0, 100, 44, 44);
[btn1 setImage:[UIImage imageNamed:@"2.jpg"] forState:UIControlStateNormal];
2)然后添加按钮到导航控制器中
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn1];
导航控制器
1 设置导航控制器的背景图片
导航控制器如果为透明的话,起始坐标为(0, 64);
导航控制器如果为不透明的话,起始坐标为(0, 0);
//设置导航条背景图片,导航则会变为不透明.
[navi.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
2 设置导航控制器的背景颜色
//这时我们需要判断我们的系统版本号是不是大于7
首先先在导航控制器1-Prefix.pch文件内,写define
#define iOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
if (iOS7)
{
navi.navigationBar.barTintColor = [UIColor greenColor];
}
else
{
navi.navigationBar.tintColor = [UIColor greenColor];
3 切换到下个viewControl时隐藏导航控制器
我们想程序出来时,3秒隐藏导航控制器
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self performSelector:@selector(test) withObject:nil afterDelay:1.0f];
}
- (void)test
{
[super viewDidAppear:YES];
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
4 改变状态拦样式(变白亮点)
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
5 隐藏状态栏
//隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
return YES;
}
6 如果自定义添加一个back按钮,则系统会替我们添加一个back按钮,默认名字为back,如果我们有title,则名字会和title一致
7 在导航控制器添加按钮,跳转到其中某个viewControl界面
例:跳转到第三个viewControl界面
- (void)go3
{
UIViewController *v;
NSArray *s = self.navigationController.viewControllers;
for (UIViewController *vc in s)
{
if ([vc.title isEqualToString:@"绿色"])
{
v = vc;
break;
}
}
[self.navigationController popToViewController:v animated:YES];
}
回到根视图控制器
- (void)root
{
//直接回到根视图控制器
[self.navigationController popToRootViewControllerAnimated:YES];
}
往导航控制器的titleView里面加东西
self.navigationBar.titleView = UIButton;
这样才能显示出来!
8 uitoolbar (工具条上都是按钮)
(1)先开启toolbarHidden
navi.toolbarHidden = NO;
(2)更改toolbar的背景颜色
navi.toolbar.barTintColor = [UIColor redColor];
(2)设置toolbar上的按钮
UIBarButtonItem *forward = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward target:nil action:nil];
UIBarButtonItem *play = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlaytarget:nil action:nil];
UIBarButtonItem *pause = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:nil action:nil];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//设置toolbar上的按钮
self.toolbarItems = @[forward, space, play, space, pause];
9 UISegmentControl:分段控制器
tupian 可以是字符串或者图片
NSArray *ary = @[@"1", @"2", @"3", @"4", @"5"];
UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:ary];
seg.frame = CGRectMake(30, 50, 200, 30);
//设置默认选项(第五个)
seg.selectedSegmentIndex = 4;
[seg addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:seg];
}
- (void)change:(UISegmentedControl *)sender
{
int i = sender.selectedSegmentIndex;
switch (i) {
case 0:
NSLog(@"按价格排列");
break;
case 1:
NSLog(@"按销量排列");
default:
break;
}
}
10 UISlider 滑块
tupian
UISlider *slider = [[UISlider alloc] init];
[slider setThumbImage:[UIImage imageNamed:@"kiss_40"] forState:UIControlStateNormal];
//slider.enabled = NO;
slider.maximumValue = 100.0;//设置最大值
slider.minimumValue = 0.0;//设置最小值
slider.value = 50; //设置默认值
slider.maximumTrackTintColor = [UIColor redColor];
slider.minimumTrackTintColor = [UIColor blackColor];
// CGAffineTransform traform = CGAffineTransformRotate(slider.transform, M_PI_2);
// slider.transform = traform;
[slider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
slider.backgroundColor = [UIColor redColor];
slider.frame = CGRectMake(10, 30, 300, 50);
[self.view addSubview:slider];
}
- (void)valueChange:(UISlider *)sender
{
CGFloat value = sender.value;
NSLog(@"value = %f", value);
}
11 UISwith 开关
tupian
UISwitch *swi = [[UISwitch alloc] init];
//改变颜色
swi.onTintColor = [UIColor redColor];
[swi addTarget:self action:@selector(swichChange:) forControlEvents:UIControlEventValueChanged];
//默认为打开状态
[swi setOn:YES animated:YES];
swi.frame = CGRectMake(10, 30, 100, 50);
[self.view addSubview:swi];
}
- (void)swichChange:(UISwitch *)sender
{
if (sender.isOn)
{
NSLog(@"开");
}
else
{
NSLog(@"关");
}
}
12 UIActivityIndicatorView 菊花
tupian
UIActivityIndicatorView *flower1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//启动动画
[flower1 startAnimating];
//停止动画,并且隐藏
//[flower1 stopAnimating];
//停止后是否隐藏,默认为YES
flower1.hidesWhenStopped = NO;
//设置颜色
flower1.color = [UIColor redColor];
//设置状态栏的网络状态 tupian
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
flower1.frame = CGRectMake(10, 30, 100, 100);
[self.view addSubview:flower1];
13 UIProgressView 进度条
tupian
UIProgressView *progressView = [[UIProgressView alloc] init];
progressView.tag = 1;
progressView.progress = 0.0;
progressView.trackTintColor = [UIColor redColor];
progressView.progressTintColor = [UIColor greenColor];
progressView.frame = CGRectMake(10, 30, 300, 50);
[self.view addSubview:progressView];
//定时器
//1.每隔多长时间
//2.谁
//3.做什么
//4.要给第3步传递的参数
//5.是否重复
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeProgress) userInfo:pro(传得时一个参数) repeats:YES];
//停止定时器,停止后必须要重新创建定时器
//[timer invalidate];
}
- (void)changeProgress
{
UIProgressView *p = (UIProgressView *)[self.view viewWithTag:1];
CGFloat newProgress = p.progress + 0.1;
[p setProgress:newProgress animated:YES];
}
14 UIStepper 计步器
tupian
UIStepper *stepper = [[UIStepper alloc] init];
//设置步长
stepper.stepValue = 3;
//设置循环
stepper.wraps = YES;
stepper.maximumValue = 10;
stepper.minimumValue = 0;
[stepper addTarget:self action:@selector(stepChange:) forControlEvents:UIControlEventValueChanged];
stepper.frame = CGRectMake(10, 30, 300, 30);
[self.view addSubview:stepper];
}
- (void)stepChange:(UIStepper *)sender
{
CGFloat value = sender.value;
NSLog(@"%f", value);
}
15 UITextView
//没有边框
UITextView *textView = [[UITextView alloc] init];
textView.frame = CGRectMake(10, 30, 200, 100);
textView.delegate = self;
//设置边框大小
textView.layer.borderWidth = 1;
textView.font = [UIFont systemFontOfSize:30];
textView.textColor = [UIColor redColor];
//设置内容
textView.text = @"hello";
必须要加这个东西,这个是在IOS7以后才出现的!
//出现光标偏移
self.automaticallyAdjustsScrollViewInsets = NO;
//隐藏键盘
//1.在旁边添加一个按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:@"发送" forState:UIControlStateNormal];
btn.frame = CGRectMake(210, 30, 50, 50);
[btn addTarget:self action:@selector(hideKeyBoard) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//2.点击空白区域
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
[tap addTarget:self action:@selector(hideKeyBoard)];
[self.view addGestureRecognizer:tap];
// [textView resignFirstResponder];
[self.view addSubview:textView];
}
//按空白或者发送键隐藏键盘
- (void)hideKeyBoard
{
[self.view endEditing:YES];
}
//可以打印用户正在输入的内容 需要代理协议 <uitextviewdelegate>
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSLog(@"%@", text);
return YES;
}
15 UITouch
《—-
1 、设置图片阴影
//设置阴影
_imageView.layer.shadowOffset = CGSizeMake(-5, 5);
_imageView.layer.shadowColor = [[UIColor lightGrayColor] CGColor];
_imageView.layer.shadowOpacity = 0.5;
2、两个动作就可以造成这个效果
//在屏幕上滑动
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//获取其中一个
UITouch *t = [touches anyObject];
//获取坐标点
CGPoint currPoint;
CGPoint prevPoint;
//当前坐标
currPoint = [t locationInView:self.view];
CGRect frame = _imageView.frame;
//当我手指还点击图片(没有离开的时候)向右滑动的时候,最多滑到160处
if (currPoint.x >= 160)
{
frame.origin.x = 160;
}
else
{
frame.origin.x = currPoint.x;
}
_imageView.frame = frame;
NSLog(@"开始:%@, %@", NSStringFromCGPoint(currPoint), NSStringFromCGPoint(prevPoint));
}
//手指离开屏幕
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
//获取坐标点
CGPoint currPoint;
//当前坐标
currPoint = [t locationInView:self.view];
CGRect frame = _imageView.frame;
//当我手指离开图片的时候,图片自动滑到100处
if (currPoint.x >= 100)
{
frame.origin.x = 100;
NSLog(@"%f", frame.origin.x);
}
[UIView animateWithDuration:0.3 animations:^{
_imageView.frame = frame;
}];
}
===============
//触摸屏幕时候触发
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//获取到用户点击的位置
//NSArray *allTouch = [touches allObjects]; //返回所有元素,返回所有点击的坐标
//获取其中一个
UITouch *t = [touches anyObject];
//获取坐标点
CGPoint currPoint;
CGPoint prevPoint;
//当前坐标
currPoint = [t locationInView:self.view];
//上一个坐标
prevPoint = [t previousLocationInView:self.view];
NSLog(@"开始:%@, %@", NSStringFromCGPoint(currPoint), NSStringFromCGPoint(prevPoint));
}
16 UITabbarController
1 设置tabbar按钮
1) 系统自带
UITabBarItem *item = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemSearch tag:0];
self.tabBarItem = item;
2) 带一张图片和文字
// 文字+图片
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"分栏红色" image:[UIImage imageNamed:@"man_30"] tag:0];
3) 带两张图片和文字
//ios7以后才可以使用
// 文字+图片+选中图片
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"红色标题" image:[UIImage imageNamed:@"man_30"] selectedImage:[UIImage imageNamed:@"messenger_30"]];
self.tabBarItem = item;
2 设置徽标(泡泡)
item.badgeValue = @"123";
3 设置应用程序的提示数字
//设置应用程序图标上的提示数字
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:10];——》这句话放在哪个VIEWCONTROL都可以
4 代理协议<UITabBarControllerDelegate>
//指定viewcontroller是否可选
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
if ([viewController.title isEqualToString:@"蓝色"])
{
return NO; //使蓝色这个无法选中
}
return YES;
}
//已经选中
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if ([viewController.title isEqualToString:@"绿色"])
{
//使绿色这个的背景颜色改变
viewController.view.backgroundColor = [UIColor blackColor];
}
}
5 保存最后一次点击的位置
再次打开时
//已经选中 这是代理协议中的方法
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSInteger index = tabBarController.selectedIndex; //获取当前被选中的viewcontroller下标
//保存用户最后一次点击的位置
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:index forKey:@"lastSelected"];
//同步
[userDefaults synchronize];
}
//将之前保存的位置取出
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//
NSInteger lastSelected = [userDefaults integerForKey:@"lastSelected"];
//赋值给selectedIndex
tb.selectedIndex = lastSelected;
6 编辑完保存拖动的顺序
//用户结束编辑 这是代理的协议
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
if (changed) //如果用户有对vc位置进行过改变
{
NSMutableArray *titleArray = [[NSMutableArray alloc] init];
for (UIViewController *vc in viewControllers)
{
//取出每个viewcontroller的title保存
[titleArray addObject:vc.title];
}
//将上述数组直接存到userDefaults中
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:titleArray forKey:@"userOrder"];
[userDefaults synchronize];
}
}
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *order = [userDefaults arrayForKey:@"userOrder"];
//原始顺序
NSArray *viewControllers = @[red, green, blue, yellow, purple, orange];
//重新组合要显示的顺序
if (order != nil)
{
NSMutableArray *newViewControllers = [[NSMutableArray alloc] init];
for (NSString *title in order) //遍历名单
{
for (UIViewController *vc in viewControllers) //遍历学生
{
if ([title isEqualToString:vc.title])
{
[newViewControllers addObject:vc];
}
}
}
//3.将要显示的控制器交由tb来管理
tb.viewControllers = newViewControllers;
}
else //第一次安装app 的时候,显示原始顺序
{
tb.viewControllers = viewControllers;
}
//设置代理,用来监听tabbar选择的变化
tb.delegate = self;
7 定制UITabBarControl(自定义)
自定义一个tabbar,继承uiview
@interface WLDTabbarView : UIView
#import "WLDTabbarView.h"
#import "WLDAppDelegate.h"
@implementation WLDTabbarView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIImageView *imagev = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
imagev.image = [UIImage imageNamed:@"tabbar_bg@2x"];
imagev.userInteractionEnabled = YES;
[self addSubview:imagev];
for (int i = 0; i < 4; i ++)
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d", i * 2 + 1]] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d", i * 2 + 2]] forState:UIControlStateSelected];
btn.frame = CGRectMake(80 * i, 0, 80, 60);
[imagev addSubview:btn];
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
btn.tag = 100 + i;
btn.adjustsImageWhenHighlighted = NO;
}
}
return self;
}
- (void)click:(UIButton *)sender
{
for (int i = 0; i < 4; i ++)
{
UIButton *btn = (UIButton *)[self viewWithTag:100 + i];
btn.selected = NO;
}
sender.selected = !sender.isSelected;
//获取到当前app的代理对象
UIApplication *app = [UIApplication sharedApplication];
WLDAppDelegate *delegate = app.delegate;
通过点击按钮,可以切换我们的viewControl
delegate.tabber.selectedIndex = sender.tag - 100;
NSLog(@"%d", sender.tag - 100);
}
然后
@interface WLDAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) UITabBarController *tabber;
@end
在@implementation WLDAppDelegate中
_tabber = [[UITabBarController alloc] init];
_tabber.viewControllers = @[navi1, navi2, navi3, navi4];
self.window.rootViewController = _tabber;
[self creatTabbar];
return YES;
}
- (void)creatTabbar
{
//隐藏tabbar
_tabber.tabBar.hidden = YES;
WLDTabbarView *tabbarView = [[WLDTabbarView alloc] initWithFrame:CGRectMake(0, 480 - 60, 320, 60)];
[self.window addSubview:tabbarView];
}
=========================================
4) 开始时隐藏自定义tabbar
[self hide];
- (void)hideTabBar
{
CGRect frame = _customerTabBar.frame;
frame.origin.y = 480;
[UIView animateWithDuration:0.3 animations:^{
_customerTabBar.frame = frame;
//设置透明度
_customerTabBar.alpha = 0;
}];
}
5) 过3秒显示tabbar
需要用到一个自带的方法
[self performSelector:@selector(showTabBar) withObject:nil afterDelay:3];
- (void)showTabBar
{
CGRect frame = _customerTabBar.frame;
frame.origin.y = 480 - CGRectGetHeight(frame);
[UIView animateWithDuration:0.3 animations:^{
_customerTabBar.frame = frame;
_customerTabBar.alpha = 1;
}];
}
6) 如果你是IOS6,你要定制自己的tabbar,就会遇到这个问题解决ios6中,viewControl中view不能全屏的问题
//把这段话弄上去就可以了
[self ios6];
- (void)ios6
{
NSArray *subs = _tb.view.subviews;
for (UIView *v in subs)
{
//将类名转换为字符串
if ([NSStringFromClass([v class]) isEqualToString:@"UITransitionView"])
{
v.frame = CGRectMake(0, 0, 320, 480);
}
}
NSLog(@"subs = %@", subs);
}
17 UIScrollView 基本操作
UIScrollView *sc = [[UIScrollView alloc] init];
sc.frame = CGRectMake(10, 30, 300, 200);
//设置scrollview的可视范围
sc.contentSize = CGSizeMake(600, 400);
//弹簧效果
sc.bounces = YES;
//设置翻页
sc.pagingEnabled = YES;
//隐藏滚动条
//垂直滚动条
sc.showsVerticalScrollIndicator = NO;
//水平滚动条
sc.showsHorizontalScrollIndicator = NO;
//将想要滚动的内容放到scrollView中
UIView *v1 = [[UIView alloc] init];
v1.frame = CGRectMake(0, 0, 300, 200);
v1.backgroundColor = [UIColor yellowColor];
UIView *v2 = [[UIView alloc] init];
v2.frame = CGRectMake(300, 0, 300, 200);
v2.backgroundColor = [UIColor blueColor];
UIView *v3 = [[UIView alloc] init];
v3.frame = CGRectMake(0, 200, 300, 200);
v3.backgroundColor = [UIColor greenColor];
UIView *v4 = [[UIView alloc] init];
v4.frame = CGRectMake(300, 200, 300, 200);
v4.backgroundColor = [UIColor blackColor];
[sc addSubview:v1];
[sc addSubview:v2];
[sc addSubview:v3];
[sc addSubview:v4];
[self.view addSubview:sc];
//设置移动偏移
sc.contentOffset = CGPointMake(20, 0);
//带动画的移动偏移
// [sc setContentOffset:CGPointMake(arc4random() % 301, arc4random() % 201) animated:YES];
定制广告条 scrollView
1) 创建scrollView
UIScrollView *sc = [[UIScrollView alloc] init];
sc.frame = CGRectMake(0, 20, 320, 150);
//可视范围
sc.contentSize = CGSizeMake(320 * 6, 150);
//翻页效果
sc.pagingEnabled = YES;
[self.view addSubview:sc];
//设置scrollview的起始位置
sc.contentOffset = CGPointMake(320, 0);
//取消水平滚动条
sc.showsHorizontalScrollIndicator = NO;
2) 创建6个UIImageView,并添加到scrollView上
for (NSInteger i = 0; i < 4; ++i)
{
NSString *name = [NSString stringWithFormat:@"%d.jpg", i + 1];
UIImage *image = [UIImage imageNamed:name];
UIImageView *v = [[UIImageView alloc] init];
v.image = image;
v.frame = CGRectMake(i * 320 + 320, 0, 320, 150);
[sc addSubview:v];
}
//实现循环滚动,在最后和最前面各添加一个冗余的view
UIImageView *last = [[UIImageView alloc] init];
UIImageView *first = [[UIImageView alloc] init];
first.frame = CGRectMake(0, 0, 320, 150);
last.frame = CGRectMake(320 * 5, 0, 320, 150);
first.image = [UIImage imageNamed:@"4.jpg"];
last.image = [UIImage imageNamed:@"1.jpg"];
[sc addSubview:first];
[sc addSubview:last];
3) 创建一个最纯的view,并添加到view中
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor lightGrayColor];
view.alpha = 0.5;
view.frame = CGRectMake(0, 150, 320, 20);
[self.view addSubview:view];
4) 创建一个pageControl,添加到最纯的view中
//用来显示页数
pageControl = [[UIPageControl alloc] init];
pageControl.frame = CGRectMake(225, -9, 95, 37);
//剩余页数颜色
pageControl.pageIndicatorTintColor = [UIColor blackColor];
//当前页数颜色
pageControl.currentPageIndicatorTintColor = [UIColor redColor];
//设置总页数
pageControl.numberOfPages = 4;
[view addSubview:pageControl];
5) 要设代理
sc.delegate = self;
6) 这是代理的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGPoint point = scrollView.contentOffset;//当前scrollView的位置
//需要根据当前的位置来设置pageControl的页数
pag.currentPage = (point.x - 320) / 320;
if (point.x == 320 * 5)//当移动到第6张的时候
{
pag.currentPage = 0;把页数置为0
scrollView.contentOffset = CGPointMake(320, 0);把scorllview的 位置改变
}
else
if (point.x == 0)
{
pag.currentPage = 4;
scrollView.contentOffset = CGPointMake(320 * 4, 0);
}
}
7)使广告条自己跳转
1))设置定时器,让其在规定的时间内触发时间
//启动定时器
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeAD) userInfo:nil repeats:YES];
2)) 触发方法
- (void)changAD
{
CGPoint point = scr.contentOffset;
point.x += 320;
pag.currentPage = (point.x - 320) / 320;
if (point.x == 320 * 5)
{
point.x = 320;
pag.currentPage = 0;
scr.contentOffset = point;
return;
}
//设置scorllView的位置
[scr setContentOffset:point animated:YES];
}
scrollView 中图片的放大缩小
UIImageView *imgView = nil;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,320, 480)];
imgView.image = [UIImage imageNamed:@"1.jpg"];
[scroll addSubview:imgView];
scroll.minimumZoomScale = 0.5f;
scroll.maximumZoomScale = 2.0f;
scroll.delegate = self;
[self.view addSubview:scroll];
}
代理方法
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return imgView;
}
18 用scrollView做进场动画->如果第一次进入,进入动画界面,不是,则进入主界面
首先在appdelegate里面
//从沙盒中取数据
NSNumber *num = [[NSUserDefaults standardUserDefaults] objectForKey:@"first"];
_isFirst = [num boolValue];
if(!_isFirst)
{
self.animationVC = [[CYAnimationViewController alloc] init];
self.window.rootViewController = self.animationVC;
}
else
{
self.window.rootViewController = self.rootVC;
}
然后写两个viewControl,一个是动画界面,一个是主界面
//动画界面
//创建scrollerview,如果滑动到最后一张,再拖拽下,就进入主界面
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
for (NSInteger i = 0; i < 4; i++) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i*320,0, 320, 480)];
imgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i+1]];
[scroll addSubview:imgView];
}
scroll.contentSize = CGSizeMake(320 * 4, 480);
scroll.pagingEnabled = YES;
scroll.delegate = self;
scroll.showsHorizontalScrollIndicator = NO;
[self.view addSubview:scroll];
}
//拖拽下,就进入主界面
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
NSInteger index = scrollView.contentOffset.x; //960
if(index > 1000)
{
CYAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
appDelegate.window.rootViewController = appDelegate.rootVC;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"first"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
============================
UIViewController *vc = nil;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL key = [userDefaults boolForKey:@"firstLuanch"];
if (!key)
{
//将字符串转换为Class(类)实例化对象的第二种方法!
vc = [[NSClassFromString(@"QFWelcomeViewController") alloc] init];
//vc = [[QFWelcomeViewController alloc] init];
[userDefaults setBool:YES forKey:@"firstLuanch"];
[userDefaults synchronize];
}
else
{
vc = [[NSClassFromString(@"QFMainViewController") alloc] init];
//vc = [[QFMainViewController alloc] init];
}
self.window.rootViewController = vc;
19 UITableView
分割线样式
//UITableViewCellSeparatorStyleNone 没分割线
//UITableViewCellSeparatorStyleSingleLine 默认的样式
tabView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//分割线颜色
tabView.separatorColor = [UIColor redColor];
1)提供数据
_dataSource = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < 4; ++i) {
[_dataSource addObject:@"张三"];
[_dataSource addObject:@"王五"];
[_dataSource addObject:@"李四"];
[_dataSource addObject:@"赵六"];
}
2)创建tableView,并遵守数据代理协议<UITableViewDataSource>
UITableView *tabv = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
//UITableViewStylePlain 列表模式
//UITableViewStyleGrouped 分组模式
列表模式:
分组模式:
[self.view addSubview:tabv];
tabv.dataSource = self;
3)设置tableView数据三部曲
//1.一共有多少段数据要显示,默认为1段
//2.每一段有多少行数据要显示
//3.每一行数据如何显示
//告诉tableview有多少段
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _dataSource.count;
}
//每段有几行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_dataSource[section] count];
}
//每行怎么显示(复用,减少cpu的压力)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell的复用
//1.从tableview中取出可以复用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//如何将数组的内容显示到cell上面
//indexPath用来表示当前行所处的位置
//indexPath.section; //当前是第几段
//indexPath.row; //当前段的第几行 == 数组下标
//2.如果复用队列中没有可复用的cell,返回nil
if (cell == nil)
{
//3.没有可复用的cell,则需要创建新的cell
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
//获取当前的段
NSArray *section = _dataSource[indexPath.section];
//再从段中获取数据
NSString *name = section[indexPath.row];
cell.textLabel.text = name;
return cell;
}
tableView常用方法
1 设置行高
首先要遵循外观的代理协议 <UITableViewDelegate>
//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//计算cell的高度
name表示每行的的字符串的CGSize,CGSize的height就是字符串的高度
NSString *name = _dataSource[indexPath.row];
CGSize size = [name sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(320, 10000)];
return size.height + 100;
}
还要在(每行怎么显示)这个方法上写上这句话
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
cell.textLabel.numberOfLines = 0;
cell.detailTextLabel.numberOfLines = 0;
2 使cell向左滑,删除cell
//向左滑删除,只要重写这个就可以了,不用在编辑模式下,就可以删除了
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
//先删除数据
[_dataSource removeObjectAtIndex:indexPath.row];
NSArray *array = @[indexPath];
[tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
}
3 定制删除按钮上的文字
//定制删除按钮上的文字内容
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"删除";
}
4 进入编辑模式1 (一般用这个)
1)self.navigationItem.rightBarButtonItem = self.editButtonItem;
2)重写系统方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[_tableView setEditing:editing animated:YES];
}
4 进入编辑模式2
1)首先要创建一个按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn addTarget:self action:@selector(entryEdit) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake(10, 30, 100, 50);
[btn setTitle:@"编辑" forState:UIControlStateNormal];
[self.view addSubview:btn];
2)按住按钮,进入编辑模式
//进入编辑模式
- (void)entryEdit
{
UITableView *tb = (UITableView *)[self.view viewWithTag:1];
//判断当前是否已经进入编辑模式
[tb setEditing:!tb.isEditing animated:YES];
}
定制某行不能编辑(第一行不能编辑)
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
//第一行不能编辑
if (indexPath.row == 0)
{
return NO;
}
return YES;
}
5 确定每一行的编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row % 2 == 0)
{
return UITableViewCellEditingStyleInsert;
}
return UITableViewCellEditingStyleDelete;
}
做出来效果如上,第一个为“加”,第二个为“减”,“加”可以添加信息,减可以删除信息!
如果要编辑时候,按“加”或者“减”,要由反应,则需要重写以下方法:
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
//判断当前的编辑模式是+还是-
//1.先将数组的内容删除
// 1-1)先找到要操作的段
NSMutableArray *section = _dataSource[indexPath.section];
switch (editingStyle) {
case UITableViewCellEditingStyleInsert:
//插入zhaoliu(下面这个方法更好!!!一定要这样写)
[self.data[indexPath.section] insertObject:@"zhaoliu" atIndex:indexPath.row];
[tabView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
break;
break;
case UITableViewCellEditingStyleDelete:
//当段中只剩下一行时候,就把段删除了(要有这个才行!!!)
if([self.data[indexPath.section] count] == 1)
{
//把一段的数据全部删除
[self.data removeObjectAtIndex:indexPath.section];
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
[indexSet addIndex:indexPath.section];
//把这段全部删除
[tabView deleteSections:indexSet withRowAnimation:UITableViewRowAnimationRight];
}
else
{
//当段中还有好几行时候,就把一行一行删除了
[self.data[indexPath.section] removeObjectAtIndex:indexPath.row];
[tabView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
break;
default:
break;
}
}
//插入数据
- (void)insertValue
{
UITableView *tb = (UITableView *)[self.view viewWithTag:1];
//1.将要插入的数据插入到数组中
// 1-1)找到要插入的段
NSMutableArray *section = _dataSource[0];
[section insertObject:@"千锋" atIndex:1];
//2.插入新的cell
// 2-1)需要自己创建一个NSIndexPath对象
NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:0];
// 2-2)将2-1创建好的对象放到数组中
NSArray *paths = @[path];
[tb insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationAutomatic];
}
6 想要在编辑模式下移动我们的cell(必须要重写我们三个方法)
//是否能移动
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
//设置不同组是否可以移动
-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
//返回值为sourceIndexPath 不能移动
//返回proposedDestinationIndexPath 可以移动
if(sourceIndexPath.section == proposedDestinationIndexPath.section)
return proposedDestinationIndexPath;
return sourceIndexPath;
}
//在这个方法里面修改数据
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
//保存数据
NSString *str = self.data[sourceIndexPath.section][sourceIndexPath.row];
//删除数据
[self.data[sourceIndexPath.section] removeObjectAtIndex:sourceIndexPath.row];
//插入数据
[self.data[destinationIndexPath.section] insertObject:str atIndex:destinationIndexPath.row];
}
7 编辑模式下的效果(两种)
//设置多选,默认为NO
tableView.allowsMultipleSelectionDuringEditing = NO;
tableView.allowsMultipleSelectionDuringEditing = YES;
8 点击按钮,滚动到指定位置(滚动到第三段第0行)
1)创建按钮
UIButton *scrollBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[scrollBtn addTarget:self action:@selector(scrollTableView) forControlEvents:UIControlEventTouchUpInside];
scrollBtn.frame = CGRectMake(220, 30, 100, 50);
[scrollBtn setTitle:@"滚动" forState:UIControlStateNormal];
[self.view addSubview:scrollBtn];
2) 触发方法
//滚动到指定位置
- (void)scrollTableView
{
UITableView *tb = (UITableView *)[self.view viewWithTag:1];
NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:3];
//滚动到指定位置
//UITableViewScrollPositionTop 指定path的cell在最上面
//UITableViewScrollPositionMiddle 指定path的cell在中间
//UITableViewScrollPositionBottom 指定path的cell在底部
[tb scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
9 在平时时候,点击cell的时候,触发事件(点击王五-2-1时,打印信息)
//点击cell时触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *section = _dataSource[indexPath.section];
NSString *name = section[indexPath.row];
NSLog(@"name = %@", name);
}
10 设置段索引
//设置段索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
//可以是任何字符串,如果索引数超过段数,点击后面的段没有反应
NSArray *titles = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7"];
return titles;
}
11 设置段头段尾的标题
//设置段头和段尾标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *s = [NSString stringWithFormat:@"第 %d 段段头", section];
return s;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
NSString *s = [NSString stringWithFormat:@"第 %d 段段尾", section];
return s;
}
12 表头表尾(表头表尾的大小不限制)
tableView.tableHeaderView = sc;
tableView.tableFooterView = footView;
13 搜索框
设置代理UITableViewDataSource, UISearchDisplayDelegate
—》
//1.创建搜索框
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];(一般为44)
searchBar.placeholder = @"请输入关键字";
//2.监听搜索事件
//不是ViewController的子类,主要是为搜索做服务的
UISearchDisplayController *_displayController;(必须声明为成员变量!!!!)
_displayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
//三个代理
_displayController.delegate = self;
//5.下面两个代理和tableView一样,只是名字不一样!
_displayController.searchResultsDataSource = self;
_displayController.searchResultsDelegate = self;
tableView.tableHeaderView = searchBar;
//4.将过滤好的数据单独使用一个数据存放
NSMutableArray *_searchResult = [[NSMutableArray alloc] init];
如果用xib创建
应写搜索框注册xib,并实例化更过的cell
[_displayControl.searchResultsTableView registerNib:[UINib nibWithNibName:@"WLDTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell_search"];
}
//完成数据的过滤
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
NSLog(@"%@", searchString);
//每次过滤之前都要将之前的数据清空
[_searchResult removeAllObjects];
//3.在搜索事件中对数据进行过滤处理
for (NSString *name in _dataSource)
{
NSRange range = [name rangeOfString:searchString];
if (range.location != NSNotFound)
{
[_searchResult addObject:name];
}
}
NSLog(@"%@", _searchResult);
return YES;
}
还有继续改下tabelView三步曲
//有几段
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView == searchDisplay.searchResultsTableView)
{
return 1;
}
return _dataSource.count;
}
//有几行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == searchDisplay.searchResultsTableView)
{
return _searchResult.count;
}
return [_dataSource[section] count];
}
//每行怎么显示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
NSMutableArray *section = _dataSource[indexPath.section];
if (tableView == searchDisplay.searchResultsTableView)
{
cell.textLabel.text = _searchResult[indexPath.row];
}
else
{
cell.textLabel.text = section[indexPath.row];
}
return cell;
=========================
xib
WLDTableViewCell *cell;
if (tableView == _displayControl.searchResultsTableView)
{
cell = [tableView dequeueReusableCellWithIdentifier:@"cell_search"];
WLDCellDataModel *dataModel = _searchData[indexPath.row];
[cell fillCellWithData:dataModel];
}
else
{
cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
WLDCellDataModel *dataModel = _dataSource[indexPath.row];
[cell fillCellWithData:dataModel];
}
}
修改段头字符串(按系统来修改)
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"段头eklfj";
}
14 定制段头内容(自定义段头需要在这个方法内进行修改)
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 40;
}
//定制每段段头显示内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
QFHeadView *v = [[QFHeadView alloc] initWithFrame:CGRectMake(0, 0, 320, 40) section:section];
如果是用xib写的,用init方法找不到我们的xib,这时候我们会用以下方法,初始化。
NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"WLDPersonSectionView(XIb名字)” owner:self options:nil];
WLDPersonSectionView *sectionView = array[0];
//记录当前段的编号
v.tag = section;
//让自己的view继承自UIControl,可以利用系统现成的方法来实现事件的监听
[v addTarget:self action:@selector(expand:) forControlEvents:UIControlEventTouchUpInside];
v.b ackgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 + 0.2 green:arc4random() % 256 / 255.0 + 0.2 blue:arc4random() % 256 / 255.0 + 0.2 alpha:1];
return v;
}
15 点击段头可以折叠(如下图)
—》
1)首先段头点击触发方法
//定制每段段头显示内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
QFHeadView *v = [[QFHeadView alloc] initWithFrame:CGRectMake(0, 0, 320, 40) section:section];
//记录当前段的编号
v.tag = section;
//让自己的view继承自UIControl,可以利用系统现成的方法来实现事件的监听
[v addTarget:self action:@selector(expand:) forControlEvents:UIControlEventTouchUpInside];
v.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 + 0.2 green:arc4random() % 256 / 255.0 + 0.2 blue:arc4random() % 256 / 255.0 + 0.2 alpha:1];
return v;
}
2)使段头模型一个属性(close)改变,并刷新我们点击的那个段
//使其中一段折叠
- (void)expand:(QFHeadView *)sender
{
//1.保存段的编号
//2.在事件处理函数中获取当前段的编号
//3.通过该编号获取到当前段的信息
//获取段的信息(第几段里面的东西)
QFSectionModal *section = _dataSource[sender.tag];
section.close = !section.isClose;
//重新触发代理方法,所有的代理方法都会重新过一遍
UITableView *tb = (UITableView *)[self.view viewWithTag:1];
//刷新段
NSMutableIndexSet *set = [[NSMutableIndexSet alloc] init];
//刷新当前段
[set addIndex:sender.tag];
//刷新当前段
[tb reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
//刷新行
//tb reloadRowsAtIndexPaths:<#(NSArray *)#> withRowAnimation:<#(UITableViewRowAnimation)#>
}
3)使行数为0 (就可以折叠)
//2.每段多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//获取当前段信息
QFSectionModal *s = _dataSource[section];
if (s.isClose)
{
NSLog(@"关闭");
return 0;
}
//返回真实的行数
return s.rows.count;
}
16 多项删除
1)首先进入编辑模式
//进入编辑模式
- (void)entryEdit
{
UITableView *tb = (UITableView *)[self.view viewWithTag:1];
tb.editing = !tb.isEditing;
}
2)点击删除,触发事件
//确定删除
- (void)commitEdit
{
UITableView *tb = (UITableView *)[self.view viewWithTag:1];
//获取用户当前所选的内容
NSArray *rows = tb.indexPathsForSelectedRows;
//删除数据
//分段处理
//获取总段数
NSInteger count = _dataSource.count;
for (NSInteger i = 0; i < count; ++i)
{
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
for (NSIndexPath *path in rows)
{
NSLog(@"%@", path);
if (path.section == i)
{
[indexSet addIndex:path.row];
}
}
//删除当前段的元素
NSMutableArray *section = _dataSource[i];
[section removeObjectsAtIndexes:indexSet];
}
//处理UI
[tb deleteRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationAutomatic];
}
17 自定义cell (xib 或者 不用xib)
首先建立一个xib
1)继承我们自己的tableViewCell
2)连线
3) 在自己的tableViewCell中写个方法(把数据加载到模型中):
- (void)fillCellWithData:(WLDData *)DataModel
然后加载xib
//加载xib
UINib *nib = [UINib nibWithNibName:@"WLDTableViewCell" bundle:nil];
//注册xib,并且会实例化足够多的cell
[_tab registerNib:nib forCellReuseIdentifier:@"cell"];
或者不用xib (控件放在contentView上面)
//注册自定义cell对象
[_tableView registerClass:[QFTableViewCell class] forCellReuseIdentifier:@"cell"];
自定义cell
//每行怎么显示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//注册cell
WLDTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//添加数据
WLDData *dataModel = _dataSource[indexPath.row];
[cell fillCellWithData:dataModel];
在cell的最右侧弄个控件(可以是自定义的,也可以是系统自带的)
如图
//定制右侧显示的内容
cell.accessoryType = XXX;
/*
UITableViewCellAccessoryNone,
UITableViewCellAccessoryDisclosureIndicator, >
UITableViewCellAccessoryDetailDisclosureButton, i>
UITableViewCellAccessoryCheckmark, √
UITableViewCellAccessoryDetailButton i
*/
return cell;
}
18 在导航控制器上加一个tabelView,出现视图偏移
必须要加这个东西,这个是在IOS7以后才出现的!
//不允许调整scrollview的位置
self.automaticallyAdjustsScrollViewInsets = NO;
// Do any additional setup after loading the view.
UITableView *tb = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 320, 480 - 64) style:UITableViewStylePlain];
19 按住一个按钮,然后跳出这个框
在头文件要遵循协议就可以了UIAlertViewDelegate,
UIAlertView
- (void)showAlertView
{
//对话框
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示框" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//风格
/*
UIAlertViewStyleSecureTextInput, 密码框
UIAlertViewStylePlainTextInput, 文本框
UIAlertViewStyleLoginAndPasswordInput 文本+密码
*/
alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
//显示对话框
[alert show];
}
点击确定时候,触发方法里面0,点击取消时触发下面方法里面1
//获取用户点击的按钮 UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"+++");
if (buttonIndex == 0)
{
//获取文本框和密码框
UITextField *t1 = [alertView textFieldAtIndex:0];
UITextField *t2 = [alertView textFieldAtIndex:1];
NSLog(@"确定:%@, %@", t1.text, t2.text);
}
else if (buttonIndex == 1)
{
NSLog(@"取消");
}
}
20 按住一个按钮,跳出这个框
在头文件要遵循协议就可以了 UIActionSheetDelegate
UIActionSheet
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除所有" otherButtonTitles:@"1", @"2", @"3", @"4", nil];
//在指定view上显示
[sheet showInView:self.view];
//监听ActionSheet按钮
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"index = %d", buttonIndex);
}
21 点击按钮把照片保存到系统相册中
- (void)saveToAlbum
{
//保存相片到相册
UIImage *image = [UIImage imageNamed:@"3.jpg"];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
//保存到相册的话就打印成功
- (void) image: (UIImage *) image
didFinishSavingWithError: (NSError *) error
contextInfo: (void *) contextInfo
{
if (error != nil)
{
NSLog(@"失败:%@", error);
}
else
{
NSLog(@"成功");
}
}
22 从相册选择图片显示在屏幕上
在头文件遵守代理方法
@interface QFViewController : UIViewController <UIImagePickerControllerDelegate>
//从相册选择图片显示到屏幕上
- (void)image1
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
//指定从哪里获取照片
//数据源
//UIImagePickerControllerSourceTypePhotoLibrary 系统相册
//UIImagePickerControllerSourceTypeCamera 摄像头
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//获取选中图片并且显示
UIImage *image = info[UIImagePickerControllerOriginalImage];
_imageView.image = image;
[picker dismissViewControllerAnimated:YES completion:nil];
}
代理==—==-=-=-=-=—非常好
//Controller2 委托 Controller1 接收处理好的数据
controller2做不了,让controller1做事
// c2被代理 c1代理
//1、建立协议
//2、c1 遵守并实现协议
//3、c1 设置代理对象 c2.delegate = self;
//3、c2 中声明代理成员
//4、c2 [self.delegate displayData:@"vc2回传的数据"];
写文件,读文件
写文件:
NSString *str = [NSString stringWithContentsOfFile:@"/Users/lcy/Desktop/test" encoding:NSUTF8StringEncoding error:nil];
读文件:
NSString *str = [NSString stringWithContentsOfFile:@"/Users/lcy/Desktop/test" encoding:NSUTF8StringEncoding error:nil];
通知中心:(1 对 多)
首先如果a 传给 b
a是发送者
b是接收者
首先在b上先初始化一个通知中心
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvMes:) name:@"name" object:nil];
}
然后写recvMes:方法(可以接收从通知中心那里传来的值)
-(void)recvMes:(NSNotification *)no
{
switch ([[no object] boolValue]) {
case YES:
self.view.backgroundColor = [UIColor redColor];
break;
case NO:
self.view.backgroundColor = [UIColor greenColor];
break;
default:
break;
}
}
在a上,点击开关switch,改变开关的值,然后发送值给通知中心
- (IBAction)valueChange:(id)sender {
UISwitch *sw = (UISwitch *)sender;
[[NSNotificationCenter defaultCenter] postNotificationName:@"name" object:[NSNumber numberWithBool:sw.on]];
}
手势:
缩放手势:
-(void)pinch:(UIPinchGestureRecognizer *)pin
{
NSLog(@"%f",pin.scale);
_imgView.transform = CGAffineTransformScale(_imgView.transform, pin.scale, pin.scale);
//重置
pin.scale = 1.0f;
}
旋转手势:
-(void)rotation:(UIRotationGestureRecognizer *)sender
{
_imgView.transform = CGAffineTransformRotate(_imgView.transform, sender.rotation);
sender.rotation = 0.0f;
}
快速滑动手势:
-(void)swipeGesture
{
UISwipeGestureRecognizer *swip1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
//快速向左滑动
swip1.direction = UISwipeGestureRecognizerDirectionLeft;
[_imgView addGestureRecognizer:swip1];
UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
//快速向右滑动
swip.direction = UISwipeGestureRecognizerDirectionRight; //3
[_imgView addGestureRecognizer:swip];
}
-(void)swip:(UISwipeGestureRecognizer *)sender
{
switch (sender.direction) {
case 1:
//如果向左滑,图片应该怎么样
break;
case 2:
break;
default:
break;
}
}
滑动手势:(侧滑)
-(void)pan:(UIPanGestureRecognizer *)sender
{
switch (sender.state) {
//开始滑动
case UIGestureRecognizerStateBegan:
{
_beginPoint = [sender locationInView:self.view];
_curPoint = self.imgView.center;
}
break;
//滑动过程中
case UIGestureRecognizerStateChanged:
{
CGPoint point = [sender locationInView:self.view];
NSInteger x_offset = point.x - _beginPoint.x;
NSInteger y_offset = point.y - _beginPoint.y;
//现在的坐标+滑动的坐标
_imgView.center = CGPointMake(_curPoint.x + x_offset, _curPoint.y + y_offset);
}
break;
case UIGestureRecognizerStateEnded:
break;
default:
break;
}
}
长按手势:
-(void)longPressGuesture
{
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[_imgView addGestureRecognizer:longPress];
}