温故而知新,UI学习中的大部分控件及常用的基础都整理了一下,很长~~~~~~~~~很长!!!!!!!
生命周期,生命周期,生命周期,重要的事要说三遍,战五渣的我最常用的好像只有Viewwillappear吧
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//得到手机主屏幕尺寸
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
//把self.window 作为主窗体在界面显示出来
[self.window makeKeyAndVisible];
return YES;
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark View
- (void)View{
//UIWindow是应用程序的窗体,所有的界面都显示在UIWindow上
//一般情况下一个应用程序只有一个UIWindow,它类似与画布,所有的界面都在上面描绘
//initWithFrame 传给它一个显示的区域大小,作为根都是屏幕大小
//使用UIScreen 获取屏幕的大小,bounds就是屏幕的宽高
//CGRect描绘一个矩形,指定原点和宽高即可
CGRect rect = [UIScreen mainScreen].bounds;
NSLog(@"screen bounds%@",NSStringFromCGRect(rect));
//iphone的屏幕坐标原点在左上角,x轴向右增加,y轴向下增加
self.window = [[UIWindow alloc]initWithFrame:rect];
//设置window的背景色,backgroundColor
//在ios中使用UIColor代表颜色,也可以指定red green blue三元色来指定
self.window.backgroundColor = [UIColor orangeColor];
//UIView :view 是代表视图,一个可见的显示区域
UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(10, 20, 200, 200)];
view1.backgroundColor = [UIColor redColor];
//所有要显示的控件都必须最终添加到window上,才能显示出来、
//addSubView:添加一个子视图,这样view1就和window发生了关联
//window就是view1的父视图,view1就是子视图
[self.window addSubview:view1];
//指定frame时,原点的坐标系是父视图的坐标系
UIView *subView1 = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
subView1.backgroundColor = [UIColor blueColor];
//把subView1添加到view1上
[view1 addSubview:subView1];
//根据自身的宽高加中心点的方式指定一个显示区域
UIView *view2 = [[UIView alloc]init];
//指定bounds时,x,y坐标由于是参考自身的坐标系所以永远为0,只需要指定宽高即可
//center 中心点
view2.bounds = CGRectMake(0, 0, 150, 150);
//center中心点的坐标系是参考父视图
view2.center = CGPointMake(200, 300);
view2.backgroundColor = [UIColor blackColor];
//把通过指定bounds和center界定出来的view,添加到windows上
[self.window addSubview:view2];
//frame 本身就是靠bounds + center 计算出来的
[self.window bringSubviewToFront:view];
//把某一个view放到最下面
//[self.window sendSubviewToBack:<#(UIView *)#>];
//[self.window insertSubview:(UIView *) aboveSubview:(UIView *)];
//[self.window insertSubview:<#(UIView *)#> belowSubview:<#(UIView *)#>];
//[self.window insertSubview:<#(UIView *)#> atIndex:<#(NSInteger)#>]
//指定角的半径
View.layer.cornerRadius = 50;
View.layer.borderColor = [UIColor redColor].CGColor;
View.layer.borderWidth = 2;
//layer:
//1:每一个view都会对应一个layer,layer帮我们做的事情是渲染view的内容
//2:layer中有一些属性是view没有的,这样我们可以对UIView做进一步的设置
//3:所有发生在view上的动画,都是layer完成的。
//UIView的作用:1:显现layer渲染出来的界面,2:与用户进行交互
//UIViewAutoresizingFlexibleLeftMargin 子视图的左边根据父视图的大小变化而变化
//UIViewAutoresizingFlexibleWidth 子视图的宽度根据父视图的大小变化而变化
//& | !
//autoresizingMask 设置子视图怎么根据父视图的大小变化而变化的属性
blueView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
//subviews 把自己的子视图放到数组中
NSArray *subViews = self.window.subviews;
NSLog(@"%@",subViews);
//交换两个视图的次序,次序既为数组中的下表
[self.window exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
//----------------------------------------------------------------------
//UIview页面翻转动画
// UIView *redView = [self.window viewWithTag:100];
// CGRect rect = redView.frame;
//
// [UIView animateWithDuration:1 animations:^{
// CGRect newRect = CGRectInset(rect, -10, -10);
// redView.frame = newRect;
// }];
//对最上层
NSArray *subViewArray = self.window.subviews;
UIView *topView = [subViewArray objectAtIndex:1];
//动画块,注意必须成对的出现
//animationID 字符串表识一个annimation
//context:这里可以传递动画结束时还需要使用的参数
[UIView beginAnimations:nil context:nil];
//设置动画行进的速度曲线
// typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
// UIViewAnimationCurveEaseInOut, // slow at beginning and end
// UIViewAnimationCurveEaseIn, // slow at beginning
// UIViewAnimationCurveEaseOut, // slow at end
// UIViewAnimationCurveLinear
// };
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//整个动画的持续时间
[UIView setAnimationDuration:1];
//UIViewAnimationTransitionCurlUp 向上翻页
//UIViewAnimationTransitionCurlDown 向下
//UIViewAnimationTransitionFlipFromLeft 从左边翻转
//UIViewAnimationTransitionFlipFromRight 从右边翻转
//forView 是在哪一个view上做动画
//catche 是否要缓存最初捕获的页面,一般写为YES,提高效率
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.window cache:YES];
//设置动画的重复次数
[UIView setAnimationRepeatCount:1];
//是否自动翻转:YES 自动翻转
//[UIView setAnimationRepeatAutoreverses:YES];
//设置动画的代理
[UIView setAnimationDelegate:self];
//设置动画结束时调用的方法
//[UIView setAnimationDidStopSelector:@selector(annimationStop)];
// [UIView beginAnimations:<#(NSString *)#> context:<#(void *)#>];
// [UIView commitAnimations];
[UIView commitAnimations];
//把上层的view 清掉
[topView removeFromSuperview];
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark UIimageView
- (void)imageView{
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark Button
- (void)Button{
//通过系统提供的使用可以生成系统提供的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
//设置普通状态下的按钮的文本
[button setTitle:@"按钮" forState:UIControlStateNormal];
//设置文本的颜色,状态为Normal
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//高亮状态下的文本的颜色
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//使用[UIImage imageNamed:@""] 通过指定图片名称的方式来生成一个UIImage
//@2x.png
//首先UIImage imageNamed如果没指定图片的后缀,默认格式png
//@2x 意思是2倍像素
//imageNamed :文件名,首先检查是否为高清屏(视网膜屏),如果是就找文件
//文件名@2x.png,如果没有对应的@2x的图片,就使用指定的文件
UIImage *imageNormal = [UIImage imageNamed:@"bgCommon"];
UIImage *imageHightLight = [UIImage imageNamed:@"bgSelected"];
//给button设置背景图片,normal状态下
//注意:button会对图片根据button的区域大小进行拉伸,如果二者的宽高比不一致图片可能变形
[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
//指定button在highlight模式下的背景图片
[button setBackgroundImage:imageHightLight forState:UIControlStateHighlighted];
//当指定的事件(Event)发生时,调用target的selector
//UIControlEventTouchDown 一旦按钮被按下就触发的buttonClickDown
[button addTarget:self action:@selector(buttonClickDown:) forControlEvents:UIControlEventTouchDown];
//UIControlEventTouchUpInside :当手指按下后开始起来,inside意思是手指在UIButton的区域范围只你
//当button的事件UIControlEventTouchUpInside发生时,调用self 的buttonClick的方法
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark View
- (void)Lable{
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, 200, 50)];
label.backgroundColor = [UIColor greenColor];
//指定UILabel显示的文本
label.text = @"Hello world";
//指定字体颜色
label.textColor = [UIColor redColor];
//设置字体大小,默认字体大小是17
label.font = [UIFont systemFontOfSize:30];
//指定字体
//label.font = [UIFont fo];
//指定字体的左右对齐方式
//NSTextAlignmentLeft 靠左 默认
//NSTextAlignmentCenter 居中
//NSTextAlignmentRight 靠右
label.textAlignment = NSTextAlignmentCenter;
//设置为0,不限制 lable 行数
label.numberOfLines = 0;
label.text = @"Application windows are expected to have a root view controller at the end of application launch";
//设置adjustsFontSizeToFitWidth 的属性为yes,可以自动调整字体的大小以适应整个的区域
label.adjustsFontSizeToFitWidth = YES;
//自动计算要显示文本需要的区域大小
[label sizeToFit];
//如果需要自己控制换行,可以手动添加\n
label.text = @"窗前明月光\n疑似地上霜\n举头望明月\n低头思校长";
int index = 0;
//得到所有的字体家族(一个字体家族包含的字体可能由斜体,粗体,下划线)
//换行的模式,意识根据什么来进行换行
//NSLineBreakByWordWrapping 以单词为单位进行换行
//NSLineBreakByCharWrapping 以字符为单位进行换行
//截断的模式
//NSLineBreakByTruncatingHead //头部截断
//NSLineBreakByTruncatingTail //尾部截断
//NSLineBreakByTruncatingMiddle //中间不显示,使用...代替
NSArray *fontFamily = [UIFont familyNames];
for (NSString *family in fontFamily) {
//得到字体家族中字体
NSArray *fontArray = [UIFont fontNamesForFamilyName:family];
for (NSString *fontName in fontArray) {
NSLog(@"%@",fontName);
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, index*30 + 20, 200, 30)];
label.text = fontName;
label.font = [UIFont fontWithName:fontName size:15];
[self.window addSubview:label];
index++;
}
}
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark Timer计时器动画
- (void)Timer{
//Time Interval:时间间隔,指定每隔多长时间定时器触发一次,单位是秒
//target + selector :当定时器触发时,调用的方法
//userInfo:是额外的参数,通常设置为nil
//repeats:指定定时器是否一直重复,YES 一直重复 NO:不重复只触发一次
//timer会对传入的targe的进行保留,(retainCount+1),防止timer触发时,target释放掉,这里对self的retainCount加一
//等到timer停掉的时候,才把self的retainCount减一`
//定义timer每隔0.1秒触发一次
_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
//由于timer对self有保留,dealloc不会被调用
//不要在dealloc中停掉timer
//让定时器失效,真个timer停掉
[_timer invalidate];
_timer = nil;
[UIView animateWithDuration:5 animations:^{
//这里写动画的最终的状态,也就是雪花的最终位置
CGRect endFrame = CGRectMake(endXPos, 667-SNOW_H, SNOW_W, SNOW_H);
snowImageView.frame = endFrame;
snowImageView.alpha = 1.0;
} completion:^(BOOL finished) {
//把自己从自己父视图上删除
//[snowImageView removeFromSuperview];
//模拟雪花被融化掉的动画
[UIView animateWithDuration:1 animations:^{
//alpha指透明度,1完全不透明
//0 是完全透明
//对于一个UIView默认的alpha值1
snowImageView.alpha = 0.0;
} completion:^(BOOL finished) {
//这里正对alpha的动画已经结束,这是可以把视图从父视图上删除
[snowImageView removeFromSuperview];
}];
}];
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark Timer弹簧动画
- (void)vidag{
for (int index = 0; index < 4; index++) {
UIView *ballView = [self.window viewWithTag:index+BASE_TAG];
//1:duration :动画的持续时间,单位秒
//2:delay:动画延迟多长时间开始 单位秒
//3:Damping 阻尼,取值范围0~1,一般 < 0.7 晃动比较厉害,为1不会有弹簧效果
//4:Velocity:初始速度,单位 points/秒,一般设置为0就可以了
//5:options:动画的一些属性,设置速度的曲线,或者翻转的方式
//6:animations :动画内容
//7:complete:动画结束时回调的block
[UIView animateWithDuration:1 delay:0.2*index usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
// CGPoint center = ballView.center;
// CGPoint newCenter = CGPointMake(center.x, center.y - 300);
// ballView.center = newCenter;
// struct CGAffineTransform {
// CGFloat a, b, c, d;
// CGFloat tx, ty;
// };
//ad缩放 bc旋转 tx,ty位移,基础的2D矩阵
//旋转,参数指定为弧度,M_PI <-> 180
//CGAffineTransformMakeRotation(<#CGFloat angle#>)
//缩放 ,sx:指x轴缩放的比例,sy 在y轴上的缩放比例
//CGAffineTransformMakeScale(<#CGFloat sx#>, <#CGFloat sy#>)
//平移 tx:在x轴上平移 ty 是在y上平移
//CGAffineTransformMakeTranslation(<#CGFloat tx#>, <#CGFloat ty#>)
//指定在y轴上 平移
ballView.transform = CGAffineTransformMakeTranslation(0, -400);
} completion:^(BOOL finished) {
}];
}
for (int index = 0; index < 4; index++) {
UIView *ballView = [self.window viewWithTag:index+BASE_TAG];
[UIView animateWithDuration:1 delay:0.2*index usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
// CGPoint center = ballView.center;
// CGPoint newCenter = CGPointMake(center.x, center.y + 300);
// ballView.center = newCenter;
//CGAffineTransformIdentity 指定一个矩阵,
//让你的view回到最原始的状态,没有缩放,没有旋转,没有平移
ballView.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
}];
}
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark Notification 通知中心
- (void)notification{
_boy1 = [[Boy alloc]init];
//把boy添加或注册到通知中心,关注的事件是name中标示的字符串
//当其他对象发布通知时,通知中心中关注次事件的对象都会得到通知
//自动调用selector方法,即[boy findFriend:]
//注意:通知中心不会把你注册对象保留,当boy对象释放的时候,一定要把自己从通知中心中移除
//通知中心:不会对你添加的对象进行比较,可能存在一个对象多次添加到通知中心的情况,添加几次就会调用几次
//最有一个参数object:nil 不管谁发送的findFriendNotification 通知自己都会接受
//如果object,非nil,指定为一个对象,意思是只关注该对象发送的通知
//为了避免多次注册到通知中心,先把_boy1从通知中心中移除,然后再添加
[[NSNotificationCenter defaultCenter] removeObserver:_boy1];
[[NSNotificationCenter defaultCenter] addObserver:_boy1 selector:@selector(findFriend:) name:@"findFriendNotification" object:nil];
//通知传值一般写法
//发通知方:
//postNotificationName:通知的名字 object:发通知的人,一般为 self userInfo:要发送的信息是个字典(也就是要传的值)
[NSNotificationCenter defaultCenter]postNotificationName:<#(NSString *)#> object:<#(id)#> userInfo:<#(NSDictionary *)#>];
//接收方:
//addObserver: 注册人一般为 self select:收到通知后调用的方法;name:为通知名,要与发通知的名字一样 object:后面写就收谁的通知(即发通知人的名字),写 nil意思是,只要通知名一样都接收
[NSNotificationCenter defaultCenter]addObserver:<#(id)#> selector:@selector(resiveNotification:) name:<#(NSString *)#> object:<#(id)#>];
}
//调用一下方法来得到传过来的值用字典接收
- (void)resiveNotification:(NSNotification*)nitification{
NSDictionary *dic =[nitification userInfo];
}
//要注意,必须先注册过才能收到通知,对于平行页面,如 tabBar 里的各个界面用通知传值,后面的界面还没有生成,也就没有注册,可以把注册方法写到 init 中,可以实现,事先注册,可以直接得到传值
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark TextField 输入框
- (void)TextField{
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(85,20, 200, 50)];
//设置边框类型
// UITextBorderStyleNone,
// UITextBorderStyleLine,
// UITextBorderStyleBezel,
// UITextBorderStyleRoundedRect
textField.borderStyle = UITextBorderStyleRoundedRect;
//暗文
textField.secureTextEntry = YES;
//设置底部背景,通常和边框类型为None的一起使用,对于圆角类型的没有效果
textField.background = [UIImage imageNamed:@"bg.png"];
//placeholder 占位符,开始编辑后消失,主要起到提示的作用,设置后灰色显示提示
textField.placeholder = @"请输入";
//编辑后是否显示编辑的删除标识,可以把文本一次性的删除
//
//UITextFieldViewModeNever, 永不显示
//UITextFieldViewModeWhileEditing, 当编辑的时候显示
//UITextFieldViewModeUnlessEditing, 当不编辑的时候显示
//UITextFieldViewModeAlways 一直显示
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//横向居中显示
textField.textAlignment = NSTextAlignmentCenter;
//调整文本垂直方向靠上,居中,靠下
//textField.contentVerticalAlignment
//是指编辑框左边的view和右边的view
UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"qq.png"]];
imageView.frame = CGRectMake(0, 0, 30, 30);
textField.leftView = imageView;
//leftViewMode 显示的模式
textField.leftViewMode = UITextFieldViewModeAlways;
textField.rightView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"test.png"]];
textField.rightViewMode = UITextFieldViewModeAlways;
//当再次编辑时,是否把上次编辑的内容清掉
textField.clearsOnBeginEditing = YES;
//键盘类型
textField.keyboardType = UIKeyboardTypeDefault;
//设置return的类型,
textField.returnKeyType = UIReturnKeyEmergencyCall;
//设置textField的代理,这样再开始编辑。
//结束编辑调用相应的代理方法
textField.delegate = self;
//是否自动纠错
textField.autocorrectionType = NO;
//让输入框成为第一响应者,这样键盘自动弹出
//所谓第一响应者就是键盘的输入和该控件结合再一起
[textField becomeFirstResponder];
//要让键盘消失,就是让textField 不是第一相应者,这样键盘就会消失
[textField resignFirstResponder];
}
//-------------------------------------------------------------------------------------------
//UITextFiel的代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//编辑框是否可以开始编辑,返回NO,编辑框没法编辑
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField; // became first responder
{
_currentEditingTextField = textField;
NSLog(@"编辑框开始编辑");
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
//textField是否应该结束编辑,如果为NO,无法结束编辑
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField; {
NSLog(@"已经结束编辑");
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
//是否应该接受输入的string,返回的时YES表示接受输入的字符
//NO 表示不接受输入的字符
//通常使用再输入验证上
if([string isEqualToString:@"!"])
{
//表示输入0不接受
return NO;
}
//其他的字符接受
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//当return键按下时调用的的代理方法
//让键盘消失,调用resignFirstResponder
//[_currentEditingTextField resignFirstResponder];
[textField resignFirstResponder];
return YES;
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark 自定义textField键盘
- (void)自定义textField{
UITextField *textField = [[UITextField alloc]init];
//inputView 可以指定一个UIView,充当我们的输入,当指定了view后,默认键盘就不会弹出
//customKeyboardView自定义一个 View 作为键盘,坐标设为0,0即可;
textField.inputView = [self customKeyboardView];
//inputAccessoryView设置自定义键盘上面的 bar,返回一个 View 就可以坐标设为0 ,0 。
textField.inputAccessoryView = [self customAccessoryView];
//----------------------————————————————————————————
//也可以创建一个 ToolBar作为自定义键盘上面的 Bar 如下
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
toolBar.translucent = NO;
toolBar.barTintColor = [UIColor orangeColor];
//在 toolBar 上添加 item,同时可以直接添加 selector 方法
UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(itemClick:)];
item1.tag = 1;
//把所有 item 添加到 toolBar 上,用一个数组
toolBar.items = @[item,item1,item,item2,item,item3,item,item4,item];
//item 调用 select 可以进行键盘类型切换
//先拿到当前编辑的 textField,使其失去第一响应者,再设置自定义键盘,然后再设为第一响应者
UITextField *textField = [self findFirstResponder];
//先拿到当前编辑的 textField,使其失去第一响应者
[textField resignFirstResponder];
// 再设置自定义键盘
textField.inputView = [self createInputView];
// 然后再设为第一响应者
[textField becomeFirstResponder];
//缩回键盘也可以用
[self.view endEditing:YES];
// use to make the view or any subview that is the first responder resign
}
//---------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark UINavigationController
- (void)UINavigationController {
[self automaticallyAdjustsScrollViewInsets];
//UINavigationController是一个容器controller,内部存放的是UIViewController,内部自己维护一个数组,显示的内容就是他容器中的UIViewController的内容
//创建UINavigationController的时候,指定一个根
UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:firstVC];
//UINavigationController 作为容器controller的本质是内部维护了一个数组,数组中存放的都是UIViewController
//navController.viewControllers
//pushViewController 把一个UIViewController推入导航控制器
//self.navigationController 可以找到viewcontroller所在的容器
//根view通过superview找到自己父视图类似
//pushViewController:
//1:secondVC 放到了UINavigationController的容器内
//2:把secondVC.navigationController = 容器
//3:把secondVC.view显示在当前的界面上
[self.navigationController pushViewController:secondVC animated:YES];
//popViewControllerAnimated 推出到那个页面
[self.navigationController popViewControllerAnimated:YES];
popViewControllerAnimated:(BOOL)animated; // Returns the popped controller.弹出自己回到上一页面
popToViewController:(UIViewController *)viewController animated:(BOOL)animated; // Pops view controllers until the one specified is on top. Returns the popped controllers.弹出到指定页面
popToRootViewControllerAnimated:(BOOL)animated; // Pops until there's only a single view controller left on the stack. Returns the popped controllers.弹出到跟页面
//UIBarMetricsDefault 人像模式,竖屏幕
//一旦使用图片作为背景,图片的大小由要求高度 44 (@2 88)> 44会向上拉伸
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"导航背景@2x.png"] forBarMetrics:UIBarMetricsDefault];
//UIBarMetricsCompact 风景模式,也就是横屏,由于尺寸问题有可能造成图片平铺
//得到原始的图片
UIImage *image = [UIImage imageNamed:@"navBg.png"];
//创建一个可以拉伸的图片给他
//UIImageResizingModeTile, 平铺
//UIImageResizingModeStretch, 拉伸
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeStretch];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsCompact];
//如果给导航栏设置设置背景,导航栏默认为不透明,坐标从导航栏下开始
//注意:对于在导航控制器的中UIViewController,默认情况下(半透明)他的视图的坐标(0,0)点会被导航栏盖掉,整个的高度 是状态栏的20+导航栏的44 ,一共64个point
//把导航栏改为不透明
self.navigationController.navigationBar.translucent = NO;
//一旦导航栏变为不透明,视图的(0,0)点坐标是从导航栏先开始
//修改navigationBar的式样,会影响到状态栏到显示
//UIBarStyleBlack 代表黑色式样
//self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
//把导航栏修改为其他颜色
self.navigationController.navigationBar.barTintColor = [UIColor yellowColor];
//这里的tintColor可以设置回退按钮的颜色
//self.navigationController.navigationBar.tintColor = [UIColor redColor];
//修改标题的颜色,以及字体大小
//指定一个字典作为title的属性,
//key NSFontAttributeName 指定自定
//key NSForegroundColorAttributeName 指定显示的颜色
self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:30],NSForegroundColorAttributeName:[UIColor redColor]};
self.title = @"标题";
//----------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark 定制NavigationBar
//这里不是设置自身的一个回退按钮,他是设置下一个导航进来的viewController的回退BarButtonItem
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(canleBarItemClick:)];
//由于图片显示渲染的问题,导致在navigationBar上设置的图片显示有问题
UIImage *image = [UIImage imageNamed:@"rightItem.png"];
//设置显示image时的渲染模式,使用最初的图片,不需要和背景混合
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//设置ViewContrller在导航栏上的展示内容
//每一个UIViewController都有一个navigationItem,由他来设置自己在naviagitonBar上的展示内容
//回退按钮的显现次序
//1: 如果设置了leftBarButtonItem,那就显示我设置的leftBarButonItem
//2: 如果上一个UIViewContrller设置backBarButtonItem,那么显示的就是back
//3: 如果上面没有设置,查看上一个UIViewController的title是否设置如果设置显示的是上一个viewController的title
// 3.1 如果上一个title文本比较多,显示不下,直接就是用系统的Back来显示
//4: 如果说以上都没有设置,显示的是Back,系统默认的
//不想让状态栏显示,需要重写该方法
- (BOOL)prefersStatusBarHidden
{
return NO;
}
//[UIApplication sharedApplication] 得到当前应用程序的对象
//全局设置状态栏的式样,同时在info.plist中设置View Controller-base status Bar appearence 设置为NO
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//添加tap手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapEvent:)];
tap.delegate = self;
//添加一个 BOOL型成员变量_isShow;
[self.view addGestureRecognizer:tap];
- (void)handleTapEvent:(UITapGestureRecognizer*)gesture
{
_isShow = !_isShow;
//让导航栏隐藏
//[self.navigationController setNavigationBarHidden:_isShow animated:NO];
//手动让状态栏刷新
[self setNeedsStatusBarAppearanceUpdate];
}
- (BOOL)prefersStatusBarHidden
{
return _isShow;
}
事件响应链,关键时候能帮很大的忙
//事件响应链:
//1:自己处理不会再传递事件的响应,如果自己不处理交给自己的父视图处理
//2:父视图不处理-》交给父视图-》视图控制器的view-》视图控制器->UIWindow->UIApplication->Appdelegate->丢弃
//只要触摸屏幕就会调用下列方法
//这两种方式都可以让事件传递下去,优先使用super的方式传递事件
//super 不仅可以让事件进行传递下去,还会做更多的操作
//直接 nextResponder 有可能造成消息丢失
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//开始触摸
NSLog(@"ViewController:touchesBegan");
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
//触摸在移动
NSLog(@"ViewController:touchesMoved");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//触摸结束
NSLog(@"ViewController:touchesEnded");
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
//触摸取消,譬如来电时会结束当前的一个触摸
NSLog(@"ViewController:touchesCancelled");
}
//----------------------------------------------------------------------------------------------------
#pragma mark -------------------------------------
#pragma mark UITabBarController
- (void)UITabBarController{
//==============================================================
使用系统的 tabBar 来生成
//UITabBarControler也是一个容器controller,本身的view不显示,显示自己孩子的viewController
//里面维护一个数组,viewControllers包含所有的子viewController
//通常TabBarController包含navigtionControoller
FirstViewController *firstViewController = [[FirstViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:firstViewController];
//使用自定义TabBarItem,title标题
//在没有指定选中图片的时候,默认使用蓝色进行选中时候的着色
//firstViewController.tabBarItem.title //标题
//firstViewController.tabBarItem.image //未选中时的图片
//firstViewController.tabBarItem.selectedImage //选中时的图片
// item 可以自己定义 title,image
UIImage *image = [UIImage imageNamed:@"tab_c1.png"];
//渲染时不要混合,使用最原始的图片输出
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UITabBarItem *item11 = [[UITabBarItem alloc]initWithTitle:@"页面1" image:[UIImage imageNamed:@"tab_0.png"] selectedImage:image];
firstViewController.tabBarItem = item11;
UITabBarController *tabBarController = [[UITabBarController alloc]init];
//UITabBarController,维护一个数组,把生成的 viewController,加进去就可以了
//也可以 创建一个UINavigationController,用initWithRootViewController:firstViewController把firstViewController设为UINavigationController的跟页面,把UINavigationController生成的对象作为,TabBar 的一个子页面
tabBarController.viewControllers = @[firstViewController,secondViewController,thirdViewController,fourViewController,fiveViewController,sixViewController];
//可以制定tintColor给tabbarItem进行选中时的着色
tabBarController.tabBar.tintColor = [UIColor redColor];
//设置 tabBar 的颜色
tabBarController.tabBar.barTintColor = [UIColor purpleColor];
//设置tabBar的背景图片
[tabBarController.tabBar setBackgroundImage:[UIImage imageNamed:@"tab_black_bg"]];
//如果子viewController个数超过5个,UITabBarController自动帮我们声称more的导航控制器,把剩余的tabBarItem放到more对应的视图控制器之内
//设置tabBar上文字的颜色
[tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]} forState:UIControlStateNormal];
[tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateSelected];
}
#pragma mark UITabBar的代理方法
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
//纪录当前选中的是哪一个viewController
//1:获取viewController的次序
//2:保存到沙盒下
//3:从沙盒目录中读取
//4:启动后重新设置选中的次序
NSLog(@"--->%ld",tabBarController.selectedIndex);
//得到我的沙盒目录 sandbox
NSString *homePath = NSHomeDirectory();
NSLog(@"%@",homePath);
//NSUserDefaults 是使用本地化存储的方式之一,
//实现的原理是在沙盒目录下,保存的一个plist文件
//只适合保存比较少量数据,譬如用户名,密码,开机欢迎界面是否显示的标志
[[NSUserDefaults standardUserDefaults] setInteger:tabBarController.selectedIndex forKey:@"currentSelectIndex"];
//注意要调用同步方法,由于NSUserDefault不会把数据马上写到本地文件
//会有延迟,调用synchronize 同步方法,会让数据马上同步到本地文件
[[NSUserDefaults standardUserDefaults] synchronize];
//把key对应的值读取出来
[[NSUserDefaults standardUserDefaults] integerForKey:@"currentSelectIndex"];
}
#pragma mark -------------------------------------
#pragma mark 自定义 TabBar
- (void)customTabBar
{
//先把自己的tabBar栏隐藏
[self.tabBar setHidden:YES];
//使用UIImageView充当我们的背景
UIImageView *backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 667-49, 375, 49)];
backgroundView.image = [UIImage imageNamed:@"tab_black_bg@2x.png"];
backgroundView.userInteractionEnabled = YES;
[self.view addSubview:backgroundView];
NSArray *titleArray = @[@"历史",@"收藏",@"分享",@"设置"];
CGFloat buttonWidth = 375/self.viewControllers.count;
CGFloat buttonHeight = 49;
for (int index = 0; index < self.viewControllers.count;index++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:[titleArray objectAtIndex:index] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
NSString *normalImageName = [NSString stringWithFormat:@"tab_%d",index];
NSString *selectImageName = [NSString stringWithFormat:@"tab_c%d",index];
//设置button上的字体的大小
button.titleLabel.font = [UIFont systemFontOfSize:12];
[button setImage:[UIImage imageNamed:normalImageName] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:selectImageName] forState:UIControlStateSelected];
button.frame = CGRectMake(index*buttonWidth, 0, buttonWidth, buttonHeight);
//对于button可以设置他image的内边距,也可以设置title的内边距,来调整button上文字和图片的位置
//button.imageEdgeInsets 设置图片的内边距
//button.titleEdgeInsets 设置title的内边距
button.imageEdgeInsets = UIEdgeInsetsMake(1, 15, 15, 0);
button.titleEdgeInsets = UIEdgeInsetsMake(30,-25, 0, 0);
button.tag = 100 + index;
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//设置初始显示时选中第一个按钮
if (index == 0) {
button.selected = YES;
}
[backgroundView addSubview:button];
}
}
- (void)buttonClick:(UIButton*)button
{
//重置button的状态
[self resetButtonStatus];
NSInteger index = button.tag - 100;
//让button处于select状态
button.selected = YES;
//修改UITabBarControler的selectedIndex ,会导致切换到对应的页面
self.selectedIndex = index;
}
- (void)resetButtonStatus
{
for (int index = 0; index < self.viewControllers.count; index++) {
UIButton *button = (UIButton*)[self.view viewWithTag:100+index];
button.selected = NO;
}
}
//======================================================================================================
#pragma mark -------------------------------------
#pragma mark UITextView多行编辑文本框和警告框
- (void)testUITextView
{
// UITextView 是多行编辑的文本框
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 80, 150, 80)];
//背景色
textView.backgroundColor = [UIColor grayColor];
//字体
textView.font = [UIFont systemFontOfSize:20];
//文字颜色
textView.textColor = [UIColor greenColor];
//设置textView的代理
textView.delegate = self;
//自适应大小时设置为 no 不会跳动
//没有自适应大小时,设置为 yes 可以超过本身行数输入,可以滑动浏览
textView.scrollEnabled = NO;
//使用它定制键盘
//textView.inputView
}
#pragma mark UITextView代理方法
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
NSLog(@"是否开始编辑");
return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
NSLog(@"是否应该");
return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
NSLog(@"应开始编辑");
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
NSLog(@"已经结束编辑");
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//指示输入的字符是否应该接收,这里可以有自己的判断逻辑
if ([text isEqualToString:@"\n"]) {
//\n代表回车
//第一响应者的概念跟UITextField一样
[textView resignFirstResponder];
return NO;
}
return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
//输入框的文本发生了变化
NSLog(@"%@",textView.text);
//[textView sizeToFit];
CGFloat textViewWidth = textView.frame.size.width;
//文本框随文字多少大小变化
CGSize newSize = [textView sizeThatFits:CGSizeMake(textViewWidth, MAXFLOAT)];
CGRect newFrame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textViewWidth, newSize.height);
textView.frame = newFrame;
}
- (void)testUIActionSheet
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"标题" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"other" otherButtonTitles:@"A",@"B",@"C", nil];
[actionSheet showInView:self.view];
}
- (void)testUIAlertView
{
//警告框,通常使用在提示用户,或者让用户做出选择
//对于otherButtonTitles,如果不需要,直接写为nil
UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"标题" message:@"警告内容" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"A",@"B",@"C", nil];
[alterView show];
// UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"是否继续操作" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
// [alterView show];
}
#pragma mark UIActionSheet代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{ //按钮序号从上到下0——>
//还是要根据buttonIndex来决定是哪个按钮被选中
NSLog(@"%ld",buttonIndex);
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
}
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet{
// before animation and showing view
}
- (void)didPresentActionSheet:(UIActionSheet *)actionSheet{
// after animation
}
- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
// before animation and hiding view
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
// after animation
}
#pragma mark UIAlertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//注意,cancle对应的button,他的index 是0,其他的根据次序顺序排列
//这样我们根据buttonIndex来决定响应了哪一个按钮
NSLog(@"%ld",buttonIndex);
}
- (void)alertViewCancel:(UIAlertView *)alertView{
//警告框取消
}
- (void)willPresentAlertView:(UIAlertView *)alertView{
// before animation and showing view
}
- (void)didPresentAlertView:(UIAlertView *)alertView{
// after animation
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
// before animation and hiding view
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
// after animation
}
//======================================================================================================
#pragma mark -------------------------------------
#pragma mark UIScrollView滚动视图
- (void)UIScrollView{
CGRect rect = self.view.frame;
CGRect scrollViewFrame = CGRectInset(rect, 50, 100);
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:scrollViewFrame];
scrollView.backgroundColor = [UIColor redColor];
scrollView.tag = 10;
//得到文件的路径
NSString *imagePath = [[NSBundle mainBundle]pathForResource:@"3" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
//通过image.size 可以得到图片的大小,使用 image 初始化 UIImageView,直接使用图片的宽高作为 UIImage 的宽高
UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
[scrollView addSubview:imageView];
//contentSize 是指定scollView能显示的内容的大小
//如果不设置contentSize的大小默认contentSize的大小就是scrollView的view的frame的大小
scrollView.contentSize = CGSizeMake(imageView.bounds.size.width, imageView.bounds.size.height);
//scrollView是否有回弹效果
scrollView.bounces = NO;
//是否显示水平滚动条
scrollView.showsHorizontalScrollIndicator = NO;
//是否显示垂直滚动条
scrollView.showsVerticalScrollIndicator;
//重点:
//设置scrollView的内容偏移量
//cotentOffset的内容视图的左上角到scrollView左上角的一个偏移量
//contentOffset.x x轴的偏移量
//contentOffset.y y轴的偏移量
//计算时以内容视图的左上角为基准
//contentOffset默认从(0,0)开始
scrollView.contentOffset = CGPointMake(100, 0);
//设置scorllView的代理,当滚动事件事件发生时,相应的代理方法被调用
scrollView.delegate = self;
//设置scollView以分页的效果显示
scrollView.pagingEnabled = YES;
//minimumZoomScale 设置最小的放大系数
scrollView.minimumZoomScale = 1.0;
//设置最大的放大系数
scrollView.maximumZoomScale = 2.0;
//添加双击事件进行缩放
UITapGestureRecognizer *tapGestrue = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapEvent:)];
tapGestrue.numberOfTapsRequired = 2;
[scrollView addGestureRecognizer:tapGestrue];
[self.view addSubview:scrollView];
}
- (void)handleTapEvent:(UITapGestureRecognizer*)gesture
{
static BOOL isZooming = NO;
UIScrollView *scrollView = (UIScrollView*)[self.view viewWithTag:100];
if (isZooming) {
[scrollView setZoomScale:1.0 animated:YES];
}else{
//scrollView.zoomScale = 2.0;
[scrollView setZoomScale:2.0 animated:YES];
}
isZooming = !isZooming;
}
#pragma mark UIScrollViewDelegate
//只要scrollView滚动就会调用该方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//由于该方法在视图滚动中一直调用,所以不要在这里做耗时的计算
NSLog(@"视图滚动");
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
NSLog(@"滚动视图内容即将被拖动");
}
//decelerate 指定是否有减速动作
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSLog(@"滚动视图的内容已经结束拖动");
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
NSLog(@"即将开始减速");
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(@"减速结束,内容视图停止");
}
//指定在scollView上哪一个视图被缩放
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return [scrollView.subviews objectAtIndex:0];
}
- (void)createPageControl
{
_pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
_pageControl.center = CGPointMake(_scrollView.center.x,_scrollView.center.y+_scrollView.bounds.size.height/2-20);
//指定pageController有多少页,由他决定圆点的个数
_pageControl.numberOfPages = 6;
//pageIndicatorTintColor 圆点的颜色
_pageControl.pageIndicatorTintColor = [UIColor blueColor];
//currentPageIndicatorTintColor 当前页的颜色
_pageControl.currentPageIndicatorTintColor = [UIColor redColor];
//_pageControl.userInteractionEnabled = NO;
//给pageControl 绑定valueChanged事件
[_pageControl addTarget:self action:@selector(pageControllChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_pageControl];
}
- (void)pageControllChanged:(UIPageControl*)pageControl
{
//首先得到pageControl目前显示的是哪一页
NSInteger currentPage = pageControl.currentPage;
CGPoint offset = CGPointMake(currentPage*_scrollView.bounds.size.width, 0);
//需要使用代码的方式滚动到相应的位置
[_scrollView setContentOffset:offset animated:YES];
}
#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)createContentImageViews
{
for (int index = 1; index <= 6; index++) {
NSString *imageName = [NSString stringWithFormat:@"%d.png",index];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((index-1)*_scrollView.bounds.size.width, 0, _scrollView.bounds.size.width, _scrollView.bounds.size.height)];
imageView.image = image;
[_scrollView addSubview:imageView];
}
//这里设置以下contentSize的大小,指定scrollView显示内容的区域大小
_scrollView.contentSize = CGSizeMake(6*_scrollView.bounds.size.width, _scrollView.bounds.size.height);
}
//只要设置了scrollView的分页显示,当手动(使用手指)滚动结束后,该代理方法会被调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(@"scrollViewDidEndDecelerating");
//得到当前的偏移
CGPoint offset = scrollView.contentOffset;
NSLog(@"offset x = %f y = %f",offset.x,offset.y);
//使用偏移量计算页码
NSInteger pageNumber = offset.x/scrollView.bounds.size.width;
NSLog(@"pageNumber = %ld",pageNumber);
//设置pageController的当前页,对应的原点高亮显示
_pageControl.currentPage = pageNumber;
}
//该代理是使用代码的方式设置contentOffset后的代理
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
NSLog(@"scrollViewDidEndScrollingAnimation");
}