UIKit笔记大全

1.0 用代码创建界面

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc]init];//1.创建界面显示的基础对象window (手机画布)
    self.window.frame = [[UIScreen mainScreen] bounds];//2.设置界面的大小和设备的屏幕一样大
    self.window.backgroundColor = [UIColor redColor]; //3.设置window的背景颜色
    UIViewController *vc = [[UIViewController alloc]init]; //4.创建一个管理界面的控制器
    //5.创建一个文本框
    /*CGRect CG开头基本都是结构体 而 OC中创建结构体变量  基本都使用 结构体的名称+Make */
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(70, 50, 100, 200)];
    //6.设置文本框中的文本内容
    label.text = @"HelloWorld";
    //7.设置文本颜色 为 绿色
    label.textColor = [UIColor greenColor];
    //8.将标签控件(label) 添加到 VC 的 视图(view)中
    [vc.view addSubview:label];

    /*创建一个新的 VC*/
    UIViewController *blueVC = [[UIViewController alloc]init];
    blueVC.view.backgroundColor = [UIColor blueColor];
    [blueVC.view addSubview:label];

    //9.将VC设置为window的根视图控制器
    self.window.rootViewController = blueVC;
    //10.显示画布
    [self.window makeKeyAndVisible];

    NSLog(@"didFinishLaunchingWithOptions");
    NSLog(@"应用程序载入后执行");
    return YES;
}
  • #### 自定义视图控制器
    self.window  = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //设置window的rootViewController
    self.window.rootViewController = [[MyViewController alloc]init];
    [self.window makeKeyAndVisible];
    self.window = [[UIWindow alloc]init];
    self.window.rootViewController = [[MyViewController alloc]init];

    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
    self.window.rootViewController = navi;
    [self.window makeKeyAndVisible];

1.1 界面间的跳转

    ViewController2 *newVC = [[ViewController2 alloc]init];
    #跳转
    [self presentViewController:newVC animated:YES completion:nil]
    #返回
    [self dismissViewControllerAnimated:YES completion:nil];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //创建MYVC1
    MyViewController1 *myVc1 = [[MyViewController1 alloc]init];
    //创建导航控制器
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:myVc1];
    self.window.rootViewController = navi;
    [self.window makeKeyAndVisible];```
```objc
    //创建目标VC
    MyViewController2 *vc2 = [[MyViewController2 alloc]init];
    //跳转
    [self.navigationController pushViewController:vc2 animated:YES];
    //返回
    [self.navigationController popViewControllerAnimated:YES];




<div class="se-preview-section-delimiter"></div>

1.2 获取屏幕宽高

    #屏幕尺寸
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    #宽高
    CGFloat screenW = screenSize.width;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    #将控件居中显示
    CGFloat labelX = (screenW - 200) * 0.5;
    CGFloat labelY = (screenH - 40) * 0.5;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(labelX, labelY, 200, 40)];




<div class="se-preview-section-delimiter"></div>

1.3 UIButton

- (void)viewDidLoad {

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 50, 100, 50);
button.backgroundColor = [UIColor redColor];
//设置button上的文字

//默认是 按键两个字
[button setTitle:@"按键" forState:UIControlStateNormal];
//高亮时(按键被按下)是 高亮两个字
 [button setTitle:@"高亮" forState:UIControlStateHighlighted];
//设置按键上的title颜色
[button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];

//设置button的图片
[button setImage:[UIImage imageNamed:@"Play-btn"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateHighlighted];
//设置button的背景图片
[button setBackgroundImage:[UIImage imageNamed:@"BTN"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"BTN2"] forState:UIControlStateHighlighted];
//设置button的失效的背景图片
[button setBackgroundImage:[UIImage imageNamed:@"disable"] forState:UIControlStateDisabled];
//让button失效
button.enabled = NO;
//设置选中背景图片
[button setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateSelected];
    button.selected = YES;

//给button添加事件
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void)buttonClick:(UIButton*)sender {
    CGRect frame = sender.frame;
    frame.size.height = 80;
    sender.frame = CGRectMake(sender.frame.origin.x,sender.frame.origin.y, 200,150);
}

//按键激活
    self.button.enabled = sender.text.length != 0;
    sender.clearButtonMode = UITextFieldViewModeWhileEditing;
    //获取第1响应者身份
    [sender becomeFirstResponder];




<div class="se-preview-section-delimiter"></div>
  • #### 循环创建两个Button
- (void)viewDidLoad {
    [super viewDidLoad];
    self.label = [[UILabel alloc]init];
    self.label.text = @"这是一个字符串";
    self.label.frame = CGRectMake(20, 50, self.view.frame.size.width - 40, 40);
    self.label.backgroundColor = [UIColor lightGrayColor];
    self.label.textColor = [UIColor whiteColor];
    [self.view addSubview:self.label];

    NSArray *buttonTitles = @[@"左边", @"右边"];
    for (int i = 0; i < 2; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        CGFloat x = i == 0 ? 20 : self.view.frame.size.width - 120 - 20;
        button.frame = CGRectMake(x, 150, 120, 50);
        button.backgroundColor = [UIColor blueColor];
        [button setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:24];
        [button setTitle:buttonTitles[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        //使用i 来设置 button 的 tag 值
        button.tag = i;
        [self.view addSubview:button];
    }
}
-(void)buttonClick:(UIButton*)sender {
    switch (sender.tag) {
        case LEFT: //左边
            self.label.textAlignment = NSTextAlignmentLeft;
            break;
        case RIGHT: //右边
            self.label.textAlignment = NSTextAlignmentRight;
            break;
    }
}




<div class="se-preview-section-delimiter"></div>

1.4 UILabel设置





<div class="se-preview-section-delimiter"></div>

#让文本居中对齐
label.textAlignment = NSTextAlignmentCenter;




<div class="se-preview-section-delimiter"></div>

#设置文本颜色
label.backgroundColor = [UIColor lightGrayColor];




<div class="se-preview-section-delimiter"></div>

#换行模式
label.lineBreakMode = NSLineBreakByTruncatingTail;




<div class="se-preview-section-delimiter"></div>

#设置字体字号
label.font = [UIFont systemFontOfSize:16];




<div class="se-preview-section-delimiter"></div>

#设置行数
label.numberOfLines = 2;




<div class="se-preview-section-delimiter"></div>

1.5 改变Frame的大小

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 200, 100)];
CGRect tempFrame = label.frame;
tempFrame.origin.x = tempFrame.origin.x + 100;
label.frame = tempFrame;

CGFloat x = 300;
label.frame = CGRectMake(label.frame.origin.x + x, label.frame.origin.y, label.frame.size.width, label.frame.size.height);




<div class="se-preview-section-delimiter"></div>

1.6 收起键盘

 //收起键盘  方式1 结束textField第一响应者身份
    [self.textField resignFirstResponder];
 //收起键盘  方式2 结束父视图编辑
    [self.view endEditing:YES];
 //成为第一响应者
    [self.pwdTextField becomeFirstResponder];




<div class="se-preview-section-delimiter"></div>

1.7 UISwitch

self.mySwitch.on = !self.mySwitch.on;
//设置开关带动画效果
[self.mySwitch setOn:!self.mySwitch.on animated:YES];
//Switch1控制Switch2
- (IBAction)switch1ValueChanged:(UISwitch*)sender {
    [self.switch2 setOn:sender.on animated:YES];
    if (sender.on) {
        self.switch2.enabled = YES;
    }else {
        self.switch2.enabled = NO;
    }
}





<div class="se-preview-section-delimiter"></div>

1.8 Alert警告框

- (IBAction)buttonClick:(id)sender {
    //需要弹出警告框
    //1.创建UIAlertController实例
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
    //2.创建意图按键
    UIAlertAction *actionYES = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //把AlertController中所有的 textField取出
        NSArray *fields = alert.textFields;
        //把 第一个添加的 textField取出
        UITextField *userNameField = fields[0];
        //把 第二个添加的 textField取出
        UITextField *pwdField = fields[1];
        //判断用户名是否是 abc  密码 是否是 123
        if ([alert.textFields[0].text isEqualToString:@"abc"] && [pwdField.text isEqualToString:@"123"]) {
            //点钟action后做什么事情
            NSLog(@"登录成功");
            //重新弹出一个对话框, title 提示  message 登录成功  action 确定
        }else {
            NSLog(@"登录失败");
            /***************************************
            //扩展作业  选做  如果失败一直弹对话框 要求重新输入,知道输入正确 弹登录成功对话框
             *****************************/
        }
    }];

    UIAlertAction *actionNO = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"actionNO 被点中");
    }];
    //3.将 alertAction 添加到 AlertController中
    [alert addAction:actionYES];
    [alert addAction:actionNO];

    //4.向AlertController中添加textField
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        //在bolck中可以设置 今天添加的textField进行设置
        //设置 占位符
        textField.placeholder = @"请重新输入用户名";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
         textField.placeholder = @"请重新输入密码";
        textField.secureTextEntry = YES;//密码样式
    }];

    //5.显示AlertController
    [self presentViewController:alert animated:YES completion:nil];

}




<div class="se-preview-section-delimiter"></div>

1.9 ActionSheet

- (IBAction)buttonClick:(id)sender {

    //1.创建alertController实例
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];
    //2.创建AlertAction
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"转发" style:UIAlertActionStyleDefault handler:nil];

    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"回复" style:UIAlertActionStyleDefault handler:nil];

    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:nil];

    //3.将 AlertAction 添加到 AlertController中
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [alert addAction:action4];

    //把alertController显示出来
    [self presentViewController:alert animated:YES completion:nil];

}```




<div class="se-preview-section-delimiter"></div>

##2.0 Delegate委托协议




<div class="se-preview-section-delimiter"></div>

```objc
@class MeViewController;

//1.制定规则   协议名称通常是类名加Delegate
@protocol MeDelegate <NSObject>
-(void)driving:(MeViewController*)meVc address:(NSString*)address;
@end

@interface MeViewController : UIViewController
//2.委托方法需要有delegate属性
@property(nonatomic,weak)id<MeDelegate> delegate;
@property(nonatomic,strong)NSString *name;
@end
//2.实现协议中的方法
-(void)driving:(MeViewController *)meVc address:(NSString *)address {
    self.label.text = [NSString stringWithFormat:@"开车送%@回%@",meVc.name,address];
    NSLog(@"开车送%@回%@",meVc.name,address);
}

- (IBAction)goNextVC:(id)sender {
    MeViewController *mc = [[MeViewController alloc]init];
    //3.设置委托方代理人为(自己)
    mc.delegate = self;
    //界面间的跳转 跳转到 MeViewController 界面
    [self presentViewController:mc animated:YES completion:nil];
   }```

```objc
- (IBAction)back:(id)sender {
    //在此时此刻需要代理人 帮我做事
    //3.在适当的时候,找代理人帮我做事
    self.name = @"xiaojian";
    [self.delegate driving:self address:@"潘家园"];
    //回到前一个界面
    [self dismissViewControllerAnimated:YES completion:nil];
}




<div class="se-preview-section-delimiter"></div>

2.1 UITextFieldDelegate

@interface MyViewController () <UITextFieldDelegate>
@end

@implementation MyViewController

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"点中了 return");
    //把键盘从该界面上收起
    [textField resignFirstResponder];
    return YES; // 返回YES  和  NO 一样
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];

    //1. 创建UITextField
    UITextField *tf = [[UITextField alloc]init];
    //2. 设置frame  (100, 100) (100, 40))
    tf.frame = CGRectMake(100, 100, 100, 40);
    //3. 设置 borderStyle 设置为 圆角矩形
    tf.borderStyle = UITextBorderStyleRoundedRect;
    //4. 设置 textField 的代理
    tf.delegate = self;
    //5. 将textField添加到 父视图中进行显示
    [self.view addSubview:tf];
}




<div class="se-preview-section-delimiter"></div>

2.2 删除子控件

    //获取保存所有子view 的数组
    NSArray *subviews = self.view.subviews;
    //取出最后一个子view
    UIView *subview = subviews.lastObject;
    //把子view自己从父view中移除
    [subview removeFromSuperview];```

 ```objc
    //得到 switch 在 子view数组中的索引
    UIView *st = [self.view viewWithTag:1];
    NSArray *subviews = self.view.subviews;
    //通过一个对象 找到对象在数组中的下标
    NSInteger index = [subviews indexOfObject:st];
    NSLog(@"%ld",(long)index);

    //取出switch
    UIView *view = [self.view viewWithTag:1];
    //将switch从 父view中移除
    [view removeFromSuperview];




<div class="se-preview-section-delimiter"></div>

2.3 NSUserDefaults

NSUserDefaults *defaults;
[defaults setObject:self.highLabel.text forKey:@"HIGH_SCORE"];//存
self.highLabel.text = [defaults objectForKey:@"HIGH_SCORE"];//取




<div class="se-preview-section-delimiter"></div>

2.4 反向传值

  • 界面一

    “`objc
    MyViewController2 *myVC2 = [[MyViewController2 alloc]init];
    myVC2.myVC1 = self;
    [self presentViewController:myVC2 animated:YES completion:nil];

    //view将要显示的时候
    -(void)viewWillAppear:(BOOL)animated {
    self.label.text = self.content;
    }

- #### 界面二





<div class="se-preview-section-delimiter"></div>

```objc
    self.myVC1.content = self.textField.text;
    //返回前一个界面
    [self dismissViewControllerAnimated:YES completion:nil];

2.5 委托的反向传值

  • #### 界面一
-(void)myViewControll2:(MyViewController2 *)myVC2 didFinishInputWithString:(NSString *)message {
    //message 就是第二界面给我的
    self.label.text = message;


}
- (IBAction)buttonClick:(id)sender {
    MyViewController2 *myVC2 = [[MyViewController2 alloc]init];
    //给myVC2这个委托人设置一个代理为self(VC1的实例)
    myVC2.delegate = self;
    [self presentViewController:myVC2 animated:YES completion:nil];
}
  • #### 界面二
@class MyViewController2;
//1.
@protocol MyViewController2Delegate <NSObject>
-(void)myViewControll2:(MyViewController2*)myVC2 didFinishInputWithString:(NSString*)message;
@end

@interface MyViewController2 : UIViewController
//2.
@property(nonatomic,weak)id<MyViewController2Delegate> delegate;

@end


- (IBAction)back:(id)sender {
    //反向传值到 前一个界面
    //如果 delegate是前 一个见面,那么这个方法是把值传给代理人(deleagte),也就是把值传给了前一个界面
    [self.delegate myViewControll2:self didFinishInputWithString:self.textField.text];

    [self dismissViewControllerAnimated:YES completion:nil];
}

2.6 Navigation导航栏

  • #### 显示导航栏
 self.navigationController.navigationBarHidden = YES;
 [self.navigationController setNavigationBarHidden:!self.navigationController.navigationBarHidden animated:YES];```

- #### 隐藏导航栏

```objc
//由系统负责隐藏 底部的各种bar
self.hidesBottomBarWhenPushed = YES;
self.navigationController.toolbarHidden = YES;
[self.navigationController setToolbarHidden:!self.navigationController.toolbarHidden animated:YES];





<div class="se-preview-section-delimiter"></div>
  • #### 配置导航栏
    //右边
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc]initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(barButtonClick:)];
    UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(barButtonClick:)];
    self.navigationItem.rightBarButtonItems = @[rightItem1, rightItem2];

    //左边
    UIBarButtonItem *leftItem1 = [[UIBarButtonItem alloc]initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:nil action:nil];
    //创建UIImage 对象,并设置图片的渲染样式始终使用原色,不受父视图的tintColor影响
    UIImage *image = [[UIImage imageNamed:@"bg_role1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftItem2 = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.leftBarButtonItems = @[leftItem1, leftItem2];

    //修改左右 按键的颜色,
    self.navigationController.navigationBar.tintColor = [UIColor greenColor];

    //中间
    self.navigationItem.title = @"中间标题";

    //修改导航条的背景
    self.navigationController.navigationBar.backgroundColor = [UIColor blueColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //设置导航条半透明状态
    self.navigationController.navigationBar.translucent = YES;
    //设置导航条 样式
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;




<div class="se-preview-section-delimiter"></div>
  • #### 设置工具栏
    //让 工具栏 显示出来
    self.navigationController.toolbarHidden = NO;
    UIBarButtonItem *toolbarIte1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRewind target:nil action:nil];
    UIBarButtonItem *toolbarIte2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:nil action:nil];
    UIBarButtonItem *toolbarIte3 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward target:nil action:nil];
    //创建50长度的木棍
    UIBarButtonItem *fixItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixItem.width = 50;
     //创建弹簧特效
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    self.toolbarItems = @[fixItem, toolbarIte1, flexibleItem, toolbarIte2, flexibleItem , toolbarIte3, fixItem];





<div class="se-preview-section-delimiter"></div>

2.7 导航控制器跳转

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"第一个导航";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(goNextVC:)];
}

-(void)goNextVC:(UIBarButtonItem*)sender {
    ViewController2 *vc2 = [[ViewController2 alloc]init];
    UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:vc2];
    //从当前导航控制器 调到 另外的导航控制器
    [self.navigationController presentViewController:navigationController animated:YES completion:nil];
}





<div class="se-preview-section-delimiter"></div>
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"第二个导航";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(back:)];
}

-(void)back:(UIBarButtonItem*)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

2.8 UIImageView

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    UIImageView *iv = [[UIImageView alloc]init];
    iv.frame = CGRectMake(50, 50, 150, 200);
    //设置 图片
    iv.image = [UIImage imageNamed:@"bg_role3"];
    iv.backgroundColor = [UIColor greenColor];
    //设置内容的显示模式
    //UIViewContentModeScaleToFill 默认:填充整个视图(ImageView),拉伸图片,高宽比例会变形
    //UIViewContentModeScaleAspectFit 保证高宽比例,尽可能的最大显示但是,两边留白
    //UIViewContentModeScaleAspectFill 保证高宽比,不留白,但是图片会显示不全
    iv.contentMode = UIViewContentModeScaleAspectFill;
    //第三种需要 配合 切割, 所有超出当前视图frame的所有子视图的显示部分都会被切割掉
    iv.clipsToBounds = YES;
    [self.view addSubview:iv];
}```

##2.9 UIScrollView&UIPageControl
```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"aa"]];


    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.tag = 100;

    scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    scrollView.contentSize = imageView.frame.size;
    scrollView.contentOffset = CGPointMake(60, 50);
    //隐藏滚动时的 滑动条
    scrollView.showsVerticalScrollIndicator = NO;

    //方式一
    //scrollView 会自动被调整到 导航条下面先显示, 如果我们不希望自动调整, 可把自动调整关闭
//    self.automaticallyAdjustsScrollViewInsets = NO;
    //方式二 修改内边距
    scrollView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
    //把要显示的内容 设置为 scrollView的子视图
    [scrollView addSubview:imageView];

    [self.view addSubview:scrollView];


    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(move:)];
}

-(void)move:(UIBarButtonItem*)sender {
    UIScrollView *sv = [self.view viewWithTag:100];
//    sv.contentOffset = CGPointMake(500, 500);
    [sv setContentOffset:CGPointMake(0, 0) animated:YES];
}




<div class="se-preview-section-delimiter"></div>
  • #### 欢迎界面
@interface MyViewController () <UIScrollViewDelegate>

@property(nonatomic,strong)UIScrollView *sv;
@property(nonatomic,strong)UIPageControl *pc;
@end

@implementation MyViewController

//scrollView的代理方法  已经滑动时调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    round  返回的是参数中浮点数 四舍五入后 的值
    //当前在 第几页上
    int currentPageNum = round(scrollView.contentOffset.x / scrollView.frame.size.width);
    self.pc.currentPage = currentPageNum;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置 scrollView相关内容
    [self configScrllView];
    [self configPageControl];
}

//设置下面的4个原点
-(void)configPageControl {
    self.pc = [[UIPageControl alloc]init];
    self.pc.frame = CGRectMake(0, self.view.frame.size.height - 60, self.view.frame.size.width, 40);
    //有几个点
    self.pc.numberOfPages = 4;
    //当前 选中的时第几个点  默认不设置是0
    self.pc.currentPage = 0;
    //每个点的颜色是什么
    self.pc.pageIndicatorTintColor = [UIColor redColor];
    //当前 选中的 点 颜色是什么
    self.pc.currentPageIndicatorTintColor = [UIColor greenColor];
    //关闭用户交互
    self.pc.userInteractionEnabled = NO;

    [self.view addSubview:self.pc];
}

-(void)configScrllView {
    //设置 scrollView 的 可见区域和屏幕一样大
    self.sv = [[UIScrollView alloc]initWithFrame:self.view.frame];
    self.sv.delegate = self;
    //设置内容区域
    self.sv.contentSize = CGSizeMake(4 * self.view.frame.size.width, self.view.frame.size.height);
    //向scrollView中添加内容
    for (int i = 0; i < 4; i++) {
        NSString *imageName = [NSString stringWithFormat:@"welcome%d", i + 1];
        UIImageView *iv = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
        iv.frame = CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
        [self.sv addSubview:iv];
        if(i == 3) {
            //在最后一个ImageView上加个 子视图 button
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake((self.view.frame.size.width - 80) * 0.5, self.view.frame.size.height - 40 - 150, 80, 40);
            button.backgroundColor = [UIColor colorWithRed:30 / 255.0 green:133 / 255.0 blue:26 / 255.0 alpha:1];
            [button setTitle:@"进入" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(goLginVc:) forControlEvents:UIControlEventTouchUpInside];
            [iv addSubview:button];
            //打开imageView 的交互
            iv.userInteractionEnabled = YES;
        }
    }
    //设置整页滑动
    self.sv.pagingEnabled = YES;
    //关闭scrollView 的 弹跳
    self.sv.bounces = NO;
    //关闭水平的滑动条
    self.sv.showsHorizontalScrollIndicator = NO;

    [self.view addSubview:self.sv];
}

-(void)goLginVc:(UIButton*)sender {
    //跳转到 登录界面
    LoginViewController *loginVc = [[LoginViewController alloc]init];

    //第三种跳转方法
    self.view.window.rootViewController = loginVc;
}

//重写父类的方法, 是在对象销毁时调用
-(void)dealloc {
    NSLog(@"欢迎界面被销毁");
}




<div class="se-preview-section-delimiter"></div>

3.0 UITableView

@interface MyViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    //记住tableView 一定要设置数据源对象
    tableView.dataSource = self;
    //设置tableView 的delegate
    tableView.delegate = self;
    [self.view addSubview:tableView];
}

//tableView  需要 三问 才能显示内容
//三问 是dataSource协议中的方法
//第1问的方法可以选择实现或不实现,如果不实现默认是1个分区
//第2问和第3问的方法,都是必须要实现的
//1.有个几个分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
//2.每个分区有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return  2; //0分区 10行
    }else if(section == 1) {
        return 3; //1分区 5行
    }else  {
        return 4; // 其他分区都是8行
    }
}
//3.每行长什么样子
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //indexPath 参数中保存 当前你要设置Cell的 分区号 和 行号
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    switch (indexPath.section) {
        case 0:
            if(indexPath.row == 0) {
                cell.textLabel.text = @"想:该问他好吗?";
            }else {
                cell.textLabel.text = @"你好吗?";
            }
            break;
        case 1:
            if (indexPath.row == 1) {
                cell.textLabel.text = @"是不是说重了?";
            }else {
                cell.textLabel.text = @"你管的着吗?";
            }
            break;
        case 2:
            cell.textLabel.text = @"滚!";
            break;
    }
    return cell;
}
//1答, 点中了做什么事
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点中了 %ld 分区 %ld 行",indexPath.section, indexPath.row);
}

//设置分区头的 文本内容
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"这是第%ld个分区头",section];
}
//设置分区头的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}




<div class="se-preview-section-delimiter"></div>
  • ###重用单元格方式一
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 10;
        case 1:
            return 5;
        default:
            return 10;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //从 一个 队列中取出一个 名字为 旺财的 空闲的cell(可以重用)
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
    if (cell == nil) {
        //如果没有取出空闲的cell(可以重用) ,则创建一个新的Cell 并给Cell 起个名字 叫旺财
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"identifier"];
    }
    //设置 cell 的三个控件 的显示
    cell.textLabel.text = @"textLabel";
    cell.detailTextLabel.text = @"detailTextLabel";
    cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
    cell.imageView.image = [UIImage imageNamed:@"head"];

    //cell 的辅助视图
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"Section %ld",section+1];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld分区%ld行被点中",indexPath.section,indexPath.row);
}




<div class="se-preview-section-delimiter"></div>
  • ###重用单元格方式二
- (void)viewDidLoad {
    [super viewDidLoad];
    //为tableView 注册单元格类型
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
//    if(cell == nil)
//    {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"];
//    }
    cell.textLabel.text = @"你好";
    cell.detailTextLabel.text = @"周杰伦";
    cell.imageView.image = [UIImage imageNamed:@"Folder"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}





<div class="se-preview-section-delimiter"></div>
  • ###自定义内容视图和辅助视图
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    UILabel *label = [cell.contentView viewWithTag:100];
    if (label == nil){ //如果 cell中没有我们自己定义的 这个Label, 那么我就创建一个添加到cell中
        label = [[UILabel alloc]init];
        label.tag = 100;
        label.frame = CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height);
        label.font = [UIFont italicSystemFontOfSize:36];
        label.textColor = [UIColor redColor];
        label.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:label];
    }

    label.text = [NSString stringWithFormat:@"该行是 %ld行",indexPath.row];

   /***** 自定义辅助视图 ****************/
    if (indexPath.row == 2) {
        UISwitch *myswitch = [[UISwitch alloc]init];
        myswitch.on = YES;
        [myswitch addTarget:self action:@selector(clickSwitch:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = myswitch;
    }else {
        cell.accessoryView = nil;
    }

    return cell;
}

-(void)clickSwitch:(UISwitch*)sender {
    NSLog(@"当前是 %@ ", sender.on ? @"开" : @"关");
}





<div class="se-preview-section-delimiter"></div>
  • ###表格数据绑定_数组
@interface MyTableViewController ()

@property(nonatomic, strong)NSArray *allCitys;
@property(nonatomic, strong)NSArray *allPopulation;
@end

@implementation MyTableViewController

//懒加载 延迟加载, 在第一次使用的时候,才创建实例
-(NSArray *)allCitys {
    if (!_allCitys) {
        _allCitys = @[@"北京",@"上海",@"广州",@"深圳",@"南京"];
    }
    return _allCitys;
}
-(NSArray *)allPopulation {
    if (!_allPopulation) {
        _allPopulation = @[@3000,@2000,@5000,@8000,@1000];
    }
    return _allPopulation;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allCitys.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //cell 重用方式 一
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = self.allCitys[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@",self.allCitys[indexPath.row],self.allPopulation[indexPath.row]];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"人口数量是%@",self.allPopulation[indexPath.row]];
    cell.imageView.image = [UIImage imageNamed:@"Folder"];
//    cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //获取点中的 Cell实例
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"%@的%@", cell.textLabel.text, cell.detailTextLabel.text);
}




<div class="se-preview-section-delimiter"></div>
  • ###分区显示数据
@implementation MyTableViewController

-(NSArray *)allcities {
    if (!_allcities) {
        _allcities = [City demoData];
    }
    return _allcities;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"城市列表";
    //向tableView 中 注册一个 Cell样式
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}





<div class="se-preview-section-delimiter"></div>

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.allcities.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    City *city = self.allcities[section];
    return city.subAreas.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   //根据 分区号 取出城市
    City *city = self.allcities[indexPath.section];
    cell.textLabel.text = city.subAreas[indexPath.row];
    return cell;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    City *city = self.allcities[section];
    UILabel *label = [[UILabel alloc]init];
//    label.frame = CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height);
    label.backgroundColor = [UIColor greenColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = city.name;
    return label;
}
//设置分区头的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

-(NSString*)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    City *city = self.allcities[section];
    return city.population;
}




<div class="se-preview-section-delimiter"></div>

3.1 表态表格

@implementation MyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置";

}




<div class="se-preview-section-delimiter"></div>

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
        case 1:
            return 3;
        case 2:
            return 2;
        default:
            return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //静态表格的Cell 同常都是 不用复用的
//    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    //设置辅助视图
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    switch (indexPath.section) {
        case 0: {
            cell.textLabel.text = @"账户与安全";
            cell.detailTextLabel.text = @"以保护";
            UIImage *image = [UIImage imageNamed:@"ProfileLockOff"];
            UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
            imageView.frame = CGRectMake(217, 13, 17, 17);
            [cell.contentView addSubview:imageView];
        }
            break;
        case 1:
            if (indexPath.row == 0) {
                cell.textLabel.text = @"新消息通知";
            }else if (indexPath.row == 1) {
                cell.textLabel.text = @"隐私";
            }else {
                cell.textLabel.text = @"通用";
            }
            break;
        case 2:
            if (indexPath.row == 0) {
                cell.textLabel.text = @"帮助与返回";
            }else if (indexPath.row == 1) {
                cell.textLabel.text = @"关于微信";
            }
            break;
        case 3: {
//            cell.textLabel.text = @"退出登录";
            UILabel *label = [[UILabel alloc]init];
            label.frame = cell.frame;
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"退出";
            //第一种 方式 自定义Cell
            [cell.contentView addSubview:label];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
            break;

    }

    return cell;
}




<div class="se-preview-section-delimiter"></div>

3.2 表态表格XIB





<div class="se-preview-section-delimiter"></div>

#import "MyTableViewController.h"

@interface MyTableViewController ()
//昵称
@property (strong, nonatomic) IBOutlet UITableViewCell *nicknameCell;

//绿钻
@property (strong, nonatomic) IBOutlet UITableViewCell *greenDiamondCell;
//免流量
@property (strong, nonatomic) IBOutlet UITableViewCell *freeDataCell;
//车载互联
@property (strong, nonatomic) IBOutlet UITableViewCell *qPlayCell;
//笛音传歌
@property (strong, nonatomic) IBOutlet UITableViewCell *translateCell;
//定时开关
@property (strong, nonatomic) IBOutlet UITableViewCell *ontimeCloseCell;
//退出
@property (strong, nonatomic) IBOutlet UITableViewCell *exitCell;

@property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;

@end

@implementation MyTableViewController

- (IBAction)switchValuechanged:(UISwitch*)sender {
    NSLog(@"%@",sender.on ? @"开" : @"关");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nicknameLabel.text = @"旺财";
}





<div class="se-preview-section-delimiter"></div>

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 1:
            return 4;
        case 2:
            return 3;
        default:
            return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return self.nicknameCell;
        case 1:
            if (indexPath.row == 0) {
                return self.greenDiamondCell;
            }else if (indexPath.row == 1) {
                return self.freeDataCell;
            }else if (indexPath.row == 2) {
                return self.qPlayCell;
            }else {
                return self.translateCell;
            }
        case 2:
            if (indexPath.row == 0) {
                return [UITableViewCell new];
            }else if (indexPath.row == 1) {
                //手动 添加辅助视图
//                self.ontimeCloseCell.accessoryView = [[UISwitch alloc]init];
                return self.ontimeCloseCell;
            }else {
               return [UITableViewCell new];
            }
        default:
            return self.exitCell;
    }
}

//设置 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        //第一个分区每行高度是 100
        return 100;
    }
    //其他都是44
    return 44;
}




<div class="se-preview-section-delimiter"></div>

3.3 下拉刷新UIRefreshControl





<div class="se-preview-section-delimiter"></div>

#import "MyTableViewController.h"
@interface MyTableViewController ()
@property(nonatomic,strong)NSMutableArray *array;
@property(nonatomic,strong)UIRefreshControl *refresh;
@end

@implementation MyTableViewController

-(NSMutableArray *)array {
    if(!_array) {
        _array = [@[@"张三", @"李四", @"王五"]
        mutableCopy];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //1. 创建 UIRefreshControl控件的实例
    self.refresh = [[UIRefreshControl alloc]init];
    //2. 将实例 赋值 给表视图控制器的 refreshControl 属性
    self.refreshControl = self.refresh;
    //3. 给 refresh 添加 valueChanged 事件的监听
    [self.refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    //当前 是否正在刷新
//    self.refresh.isRefreshing = NO;

   }

-(void)refresh:(UIRefreshControl*)sender {
//    开始刷新数据
    NSLog(@"开始刷新数据");
    //两秒钟以后执行  后 调用 加载数据方法  SEL
    [self performSelector:@selector(refreshOver:) withObject:@"赵六" afterDelay:2];
}
//加载完成  把 传入的数据 添加到tabelview
-(void)refreshOver:(NSString*)name {
    //在数组的 开始位置 插入新的数据
    [self.array insertObject:name atIndex:self.array.count];
    //更新界面
    [self.tableView reloadData];
    //修改 refreshControl , 停止旋转
    [self.refresh endRefreshing];
}





<div class="se-preview-section-delimiter"></div>

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" ];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseIdentifier"];
    }
    cell.textLabel.text = self.array[indexPath.row];
    return cell;
}




<div class="se-preview-section-delimiter"></div>

3.4 集合视图UICollectionView

@implementation MyCollectionViewController

//常量指针  指针常量  第一阶段  全局字符串
static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    //帮我们 注册好了 cell
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    //整页翻动
    self.collectionView.pagingEnabled = YES;
 }





<div class="se-preview-section-delimiter"></div>

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 20;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    cell.backgroundColor = [UIColor redColor];

    UILabel *label = [cell.contentView viewWithTag:111];
    if (label == nil) {
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
        label.tag = 111;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont boldSystemFontOfSize:30];
        label.textColor = [UIColor whiteColor];
        [cell.contentView addSubview:label];
    }
    label.text = [NSString stringWithFormat:@"%ld",indexPath.item+1];
    return cell;
}




<div class="se-preview-section-delimiter"></div>

3.5 UITabBarController


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

    //创建 UITabBarController 控制器
    UITabBarController *tabBarController = [[UITabBarController alloc]init];

    UIViewController *vc1 = [[UIViewController alloc]init];
    vc1.view.backgroundColor = [UIColor redColor];
    vc1.tabBarItem.title = @"红色";

    UIViewController *vc2 = [[UIViewController alloc]init];
    vc2.view.backgroundColor = [UIColor greenColor];
    vc2.tabBarItem.title = @"绿色";


    MyViewController3 *myvc3 = [[MyViewController3 alloc]init];
    myvc3.tabBarItem.title = @"蓝色";
    myvc3.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",11];
//    myvc3.view.backgroundColor = [UIColor whiteColor];

    //向 tabBarController 添加管理的子控制器
    [tabBarController addChildViewController:vc1];
    [tabBarController addChildViewController:vc2];
    [tabBarController addChildViewController:myvc3];
//    tabBarController.viewControllers = @[vc1,vc2,myvc3];

     //向 tabBarController 添加管理的子控制器
//    tabBarController.viewControllers = @[vc1,vc2,myvc3];

    self.window.rootViewController = tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}




<div class="se-preview-section-delimiter"></div>
  • MyViewController3
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
    self.tabBarItem.badgeValue = nil;
}





<div class="se-preview-section-delimiter"></div>

3.6 UITabBarController添加导航栏

  • AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //创建3个VC, 每个VC都在一个独立的导航控制器下
    UINavigationController *redNavi = [[UINavigationController alloc]initWithRootViewController:[[RedViewController alloc]init]];

    UINavigationController *greenNavi = [[UINavigationController alloc]initWithRootViewController:[[GreenViewController alloc]init]];

    UINavigationController *blueNavi = [[UINavigationController alloc]initWithRootViewController:[[BlueViewController alloc]initWithNibName:@"BlueViewController" bundle:nil]];

    //创建选项卡控制器 并添加被其管理的控制器
    UITabBarController *tabBarController = [[UITabBarController alloc]init];
    [tabBarController addChildViewController:redNavi];
    [tabBarController addChildViewController:greenNavi];
    [tabBarController addChildViewController:blueNavi];

    //创建window 并设置 rootViewController 为 tabBarController
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}





<div class="se-preview-section-delimiter"></div>
  • RedViewController.h
-(instancetype)init{
    if (self = [super init]) {
        //这里会把 navigationItem.title 和 tabBarItem.title 同时设置
        self.title = @"红色";
        self.tabBarItem.image = [UIImage imageNamed:@"line_bell"];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"full_bell"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    /*  设置属性字符串  */
    //创建一个属性字典
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    dic[NSForegroundColorAttributeName] = [UIColor greenColor];
    dic[NSFontAttributeName] = [UIFont systemFontOfSize:30];
    dic[NSBackgroundColorAttributeName] = [UIColor blueColor];
    //设置 导航条上title的字体
    self.navigationController.navigationBar.titleTextAttributes = dic;
}




<div class="se-preview-section-delimiter"></div>
  • GreenViewController.h
-(instancetype)init{
    if (self = [super init]) {
        //这里会把 navigationItem.title 和 tabBarItem.title 同时设置
        self.title = @"绿色";
        self.view.backgroundColor = [UIColor greenColor];
        self.tabBarItem.image = [UIImage imageNamed:@"line_cart"];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"full_cart"];
    }
    return self;
}





<div class="se-preview-section-delimiter"></div>
  • BlueViewController.h
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"蓝色";
        self.tabBarItem.image = [UIImage imageNamed:@"line_map"];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"full_map"];
        self.tabBarItem.badgeValue = @"10";
    }
    return  self;
}

- (IBAction)buttonClick:(id)sender {
    //切换到 索引为 0 的 界面
    self.tabBarController.selectedIndex = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarItem.badgeValue = nil;
}





<div class="se-preview-section-delimiter"></div>

3.7 SegmentedViewController

@interface SegmentedViewController ()
@property (weak, nonatomic) IBOutlet UIView *myView;

@end

@implementation SegmentedViewController
- (IBAction)valueChanged:(UISegmentedControl *)sender {
    UIColor *color = nil;
    switch (sender.selectedSegmentIndex) {
        case 0:
            color = [UIColor redColor];
            break;
        case 1:
            color = [UIColor greenColor];
            break;
        case 2:
            color = [UIColor blueColor];
            break;
    }
    self.myView.backgroundColor = color;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myView.backgroundColor = [UIColor redColor];
}





<div class="se-preview-section-delimiter"></div>

3.8 UIActivityIndicatorView&UIProgressView

@interface ActivityViewController ()

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activity;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property(nonatomic,strong)NSTimer *timer;

@end

@implementation ActivityViewController

- (IBAction)startAndStop:(id)sender {
    if (self.activity.isAnimating) {
        //停止定时器
        [self.timer invalidate];
        [self.activity stopAnimating];
    }else {
        //定时器  定多长时间 做什么事
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(showProgress:) userInfo:nil repeats:YES];


//        self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(showProgress:) userInfo:nil repeats:YES];
        //将创建好的 定时器添加的 主循环队列中
        [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];

        [self.activity startAnimating];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.progressView.progress = 0;
}

-(void)showProgress:(NSTimer*)sender {
    self.progressView.progress += 0.13;
    //progressView 的 progress 最大值是1, 如果大于1就等于1
    if (self.progressView.progress == 1) {
        //停止定时器
        [sender invalidate];
        //停止旋转
        [self.activity stopAnimating];
    }
}




<div class="se-preview-section-delimiter"></div>

3.9 UIDatePicker

@interface DatePickerViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *datePcker;
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation DatePickerViewController

- (IBAction)getDate:(id)sender {

//    NSDate
//    NSDateFormatter
    NSDate *date = self.datePcker.date;
    NSDateFormatter *formate =[[NSDateFormatter alloc]init];
    formate.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    self.label.text = [formate stringFromDate:date];
}





<div class="se-preview-section-delimiter"></div>

4.0 UIPickerView

@interface CityViewController () <UIPickerViewDelegate, UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property(nonatomic,strong)NSArray *allCityName;
@property(nonatomic,strong)NSArray *allAreaName;
@property(nonatomic,strong)NSDictionary *dictionary;
@end

@implementation CityViewController

-(NSDictionary*)dictionary {
    if (!_dictionary) {
        _dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
  @[@"东城",@"西城",@"朝阳",@"宣武"],@"北京",
  @[@"浦东",@"徐汇"],@"上海",
  @[@"天河",@"越秀",@"白云"],@"广东",
                       nil];
    }
    return _dictionary;
}
-(NSArray *)allCityName {
    if (!_allCityName) {
        _allCityName = self.dictionary.allKeys;
    }
    return _allCityName;
}
-(NSArray *)allAreaName {
    //默认 选中的是 城市数组中一个元素对应的区域
    if (!_allAreaName) {
        _allAreaName = [self.dictionary valueForKey:self.allCityName[0]];
    }
    return _allAreaName;
}

//多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}
//多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.allCityName.count;
    }else {
        return self.allAreaName.count;
    }
}
//每行显示什么
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return self.allCityName[row];
    }else {
        return self.allAreaName[row];
    }
}


//选中某列中某行数据时响应
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
    //获取第一列 某行对应的城市名称
    NSString *cityName = self.allCityName[row];
    //通过城市名称 从 字典把该城市的子区域 取出
    self.allAreaName = self.dictionary[cityName];
    //更细 界面
    [self.pickerView reloadComponent:1];
    //修改第二列中第一行为选中的值
    [self.pickerView selectRow:0 inComponent:1 animated:YES];
   }
}





<div class="se-preview-section-delimiter"></div>

4.1 故事版界面跳转

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    //通过 一个标示  找到 segue ,然后跳转到 segue 的目标控制器
    [self performSegueWithIdentifier:@"id" sender:nil];

}





<div class="se-preview-section-delimiter"></div>
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //获取storyboard
    //从storyboard中 通过一个 标示 取出一个场景 返回的 是场景绑定的VC实例
    UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"login"];
//    //跳转到 其他场景

    //presentViewController 跳转 欢迎界面会在下面,不会被释放
//    [self presentViewController:vc animated:YES completion:nil];

    //修改rootViewController 欢迎界面会被释放掉
    self.view.window.rootViewController = vc;

}

4.2 故事版跳故事版

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //通过名字 获取目标 故事版
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboard" bundle:nil];
    //跳转到 目标故事版中 初始的 VC
    self.view.window.rootViewController = [storyboard instantiateInitialViewController];
}

4.3 CoreGraphics

- (void)drawRect:(CGRect)rect {
//    1.获取画板  (获取系统绘制的上下环境)
    CGContextRef context = UIGraphicsGetCurrentContext();
    //2.勾勒图形
    //设置起点 (将画笔移动到制定位置)
    CGContextMoveToPoint(context, 100, 100);
    //绘制路径点
    CGContextAddLineToPoint(context, 250, 100);
    CGContextAddLineToPoint(context, 250, 300);
    CGContextAddLineToPoint(context, 100, 300);
//    CGContextAddLineToPoint(context, 100, 100);
    //封口
    CGContextClosePath(context);

    //绘制第二个图形的路径
    //设置起点 (将画笔移动到制定位置)
    CGContextMoveToPoint(context, 50, 350);
    CGContextAddLineToPoint(context, 250, 350);
    CGContextAddLineToPoint(context, 250, 400);
    CGContextAddLineToPoint(context, 100, 400);
     CGContextClosePath(context);


    //设置描边颜色
    CGContextSetStrokeColorWithColor(context,[UIColor redColor].CGColor);
    //设置填充颜色
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
    //绘制描边
    CGContextStrokePath(context);
    //绘制填充
    CGContextFillPath(context);

}

4.4 UIBezierPath

  • 画线
- (void)drawRect:(CGRect)rect {
    //1. 创建贝塞尔路径的实例
    UIBezierPath *path = [UIBezierPath bezierPath];
    //2.勾勒图形
    [path moveToPoint:CGPointMake(40, 40)];
    [path addLineToPoint:CGPointMake(250, 40)];
    [path addLineToPoint:CGPointMake(150, 140)];
//    [path addLineToPoint:CGPointMake(40, 140)];
//    [path closePath];
    //设置描边颜色
    [[UIColor redColor] setStroke];
    //设置填充色
    [[UIColor greenColor] setFill];
    //设置边的宽度
    path.lineWidth = 20;
    //焦点样式
//    kCGLineJoinMiter,  尖的
//    kCGLineJoinRound,  圆角
//    kCGLineJoinBevel   斜的 脚被砍掉
    path.lineJoinStyle = kCGLineJoinRound;
    //线两端的样式
//    kCGLineCapButt,
//    kCGLineCapRound,
//    kCGLineCapSquare
    path.lineCapStyle = kCGLineCapSquare;

    //填充
    [path fill];
    //描边
    [path stroke];

}
  • 画圆
- (void)drawRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];

    [path addArcWithCenter:CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5) radius:100 startAngle:M_PI_2 * 3 endAngle:0 clockwise:YES];
    [path moveToPoint:CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5 + 100)];
    [path addArcWithCenter:CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5) radius:100 startAngle:M_PI_2 endAngle:M_PI clockwise:YES];


    [[UIColor redColor]setStroke];
    path.lineWidth = 5;
    //绘制描边
    [path stroke];
}
  • 画进度
#import "ProgressViewController.h"
#import "ProgressView.h"
@interface ProgressViewController ()

@property (weak, nonatomic) IBOutlet ProgressView *progressView;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;

@end

@implementation ProgressViewController

- (IBAction)valueChanged:(UISlider*)sender {
    self.progressView.progressValue = sender.value;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.progressView.progressValue = self.progressSlider.value;
}
#import "ProgressView.h"

@interface ProgressView()
@property(nonatomic,strong)UILabel *label;
@end

@implementation ProgressView

//通过storyboard创建View时,会调用该初始化方法
-(instancetype)initWithCoder:(NSCoder *)coder {
    if(self = [super initWithCoder:coder]) {
        self.label = [[UILabel alloc]init];
        //设置label的属性
        self.label.frame = CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 20);
        self.label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:self.label];
    }
    return self;
}


//getter 重新定义, 基本上都是在给出属性时,需要加些判断,或做些操作
//setter 重新定义, 基本使用情况 1.希望在该属性发生变化可以额外做一些事。  2.可以对传入的参数进行控制

-(void)setProgressValue:(CGFloat)progressValue {
    _progressValue = progressValue;
    //显示下载进度
    self.label.text = [NSString stringWithFormat:@"%.2f%%",self.progressValue * 100];
    //重新绘制
    [self setNeedsDisplay];

}


- (void)drawRect:(CGRect)rect {

    UIBezierPath *path = [UIBezierPath bezierPath];
    CGPoint center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
    [path addArcWithCenter:center radius:80 startAngle:M_PI_2 * 3 endAngle:self.progressValue * M_PI * 2 + M_PI_2 * 3 clockwise:YES];
    path.lineWidth = 5;
    [[UIColor redColor]setStroke];
    [path stroke];
}
  • 画曲线
- (void)drawRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];
    //第一条曲线
    [path moveToPoint:CGPointMake(140, 40)];
    //添加 曲线的控制点
    [path addCurveToPoint:CGPointMake(40, 180) controlPoint1:CGPointMake(40, 40) controlPoint2:CGPointMake(140, 180)];

    //第二条曲线
    [path addCurveToPoint:CGPointMake(140, 320) controlPoint1:CGPointMake(140, 180) controlPoint2:CGPointMake(40, 320)];


    [[UIColor redColor]setStroke];
    path.lineWidth = 5;
    [path stroke];


    //绘制矩形
    UIBezierPath *path2 = [UIBezierPath bezierPathWithRect:CGRectMake(50, 50, 200, 150)];
    [[UIColor greenColor]setStroke];
    [path2 stroke];

    //绘制圆角矩形
    UIBezierPath *path3 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(50, 380, 200, 100) cornerRadius:10];
    path3.lineWidth = 3;
    [path3 stroke];

    //画椭圆
    UIBezierPath *path4 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 180, 100)];
    [[UIColor blueColor]setFill];
    //填充形状
    [path4 fill];

}

4.5 绘制字符串

- (void)drawRect:(CGRect)rect {
    NSString *string = @"这是一个用于绘制的字符串。。。。这是一个用于绘制的字符串。。。。这是一个用于绘制的字符串。。。。这是一个用于绘制的字符串。。。。这是一个用于绘制的字符串。。。。这是一个用于绘制的字符串。。。。";

    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:20],
        NSForegroundColorAttributeName:[UIColor redColor],
        NSBackgroundColorAttributeName:[UIColor greenColor]
    };

    //动态计算字符串高度
    //该方法会根据实际的高度,求出一个矩形并返回
    CGRect textFrame = [string boundingRectWithSize:CGSizeMake(200, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];

    [string drawInRect:CGRectMake(50, 50, textFrame.size.width, textFrame.size.height) withAttributes:attributes];


    /*
     如果动态获取 UILabel的高度
    UILabel *label = [[UILabel alloc]init];
    //不限制多少行 有多少算多少  自动换行到显示完
    label.numberOfLines = 0;
    label.text = @"textFrametextFrametextFrametextFrametextFrametextFrametextFrametextFrametextFrametextFrame";
    CGSize size = [label sizeThatFits:CGSizeMake(130, 999)];
    label.backgroundColor = [UIColor lightGrayColor];
    label.frame = CGRectMake(50, 50, size.width, size.height);
    [self addSubview:label];
     */
}

4.6 绘制图片

- (void)viewDidLoad {
    [super viewDidLoad];


    //1.创建一张临时的空白画布
    UIGraphicsBeginImageContext(self.imageView.bounds.size);
    CGRect imageRect =  CGRectMake(0, 0, 150, 150);
    //在上下文环境中写绘制代码
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect];
    [[UIColor redColor]setStroke];
    path.lineWidth = 4;
    [path stroke];
    [path addClip];

    UIImage *image = [UIImage imageNamed:@"welcome4"];
    [image drawInRect:imageRect];

    //假设: 绘制水印图片到画布上


    //用画布中的生成一个 UIImage对象
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    //关闭绘制 的上下文区间
    UIGraphicsEndImageContext();

    self.imageView.image = newImage;

}

4.7 绘制二维码

- (void)viewDidLoad {
    [super viewDidLoad];
    //1. 创建一个二维码种类的路径
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //2.恢复滤镜的默认设置
    [filter setDefaults];
    //3.把一个网站字符串转换 二进制数据
    NSString *baidu = @"http://www.baidu.com";
    NSData *data = [baidu dataUsingEncoding:NSUTF8StringEncoding];
    //4.设置 滤镜 inputMessage 属性, 该需要使用 KVC 来设置
    //通过kvc的方法  用data给filer中的inputMessage属性赋值
    [filter setValue:data forKey:@"inputMessage"];
    //5.输出二维码图片
    CIImage *image = [filter outputImage];
    UIImage *uiImage = [UIImage imageWithCIImage:image];
    //设置imageView的图片
    self.imageView.image = uiImage;
}

4.8 触摸绘图

#import "MyView.h"

@interface MyView()
@property(nonatomic,strong)UIBezierPath *bezierPath;
@end

@implementation MyView

-(UIBezierPath *)bezierPath {
    if (!_bezierPath) {
        _bezierPath = [UIBezierPath bezierPath];
        _bezierPath.lineWidth = 5;
    }
    return _bezierPath;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *pTouch = [touches anyObject];
    //将画笔移到开始触摸的位置
    [self.bezierPath moveToPoint:[pTouch locationInView:self]];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *pTouch = [touches anyObject];
    [self.bezierPath addLineToPoint:[pTouch locationInView:self]];
    //每次移动都要通知 view 重绘
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    [[UIColor redColor]setStroke];
    [self.bezierPath stroke];
}


@end

UIKit2

4.9 手势

  • 双击&单击
- (void)viewDidLoad {
    [super viewDidLoad];
    //1.创建手势  点击
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    //设置属性
    //点几次响应手势
    tap.numberOfTapsRequired = 2;
    //1个触摸点, 双击
    tap.numberOfTouchesRequired = 1;
    //将手势添加到视图中
    [self.view addGestureRecognizer:tap];

    //1.创建手势  图片单击
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap2:)];
    //将手势添加到视图中
    [self.imageView addGestureRecognizer:tap2];
}

-(void) tap:(UITapGestureRecognizer*)sender {
    NSLog(@"%@",NSStringFromCGPoint([sender locationInView:self.view]));
}
-(void) tap2:(UITapGestureRecognizer*)sender {
    NSLog(@"图片被单击");
}
  • 轻扫
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建轻松手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)];
    //设置方向
    //如果同时设置 上 下 左  右  那么上下是不响应手势的
    swipe.direction = UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown;
    //将手势添加到 视图中
    [self.view addGestureRecognizer:swipe];
}
-(void)swipe:(UISwipeGestureRecognizer*)sender {
    [self.view endEditing:YES];
}
  • 长按
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    longPress.minimumPressDuration = 2;
    [self.view addGestureRecognizer:longPress];
}

-(void)longPress:(UILongPressGestureRecognizer*)sender{
    if (sender.state == UIGestureRecognizerStateBegan) {
        NSLog(@"长按开始");
    }else if (sender.state == UIGestureRecognizerStateEnded) {
        NSLog(@"长按结束");
    }
}
  • 拖拽
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建拖拽手势
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
     //将手势添加到 imageView 身上
    [self.view addGestureRecognizer:panGR];
}
-(void)pan:(UIPanGestureRecognizer*)sender {
    //相对坐标系 原点的 位置
//    CGPoint position = [sender locationInView:self.view];
    //相对手势 起点的位置
    CGPoint position2 = [sender translationInView:self.view];
    //让 imageView 和手势做 相对变化
    CGPoint center = self.imageView.center;
    center.x += position2.x;
    center.y += position2.y;
    self.imageView.center = center;

    //把之前 累加的偏移量 清除
    [sender setTranslation:CGPointZero inView:self.view];
}
  • 捏合
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建手势
    UIPinchGestureRecognizer *pinchGR = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
    //打开imageView 的用户交互
    self.imageView.userInteractionEnabled = YES;
    //把手势添加到 imageView 上
    [self.imageView addGestureRecognizer:pinchGR];
}
-(void)pinch:(UIPinchGestureRecognizer*)sender {
    //捏合速率
    CGFloat velocity = sender.velocity;
    CGFloat scale = sender.scale;
    NSLog(@"--- 速率 %f   缩放比 %f",velocity, scale);
    //对 视图进行缩放 使用的是变形
    self.imageView.transform = CGAffineTransformMakeScale(scale, scale);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
  • 旋转
- (void)viewDidLoad {
    [super viewDidLoad];
    UIRotationGestureRecognizer *rotationGR = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotation:)];
    [self.view addGestureRecognizer:rotationGR];
}
-(void)rotation:(UIRotationGestureRecognizer*)sender {
    //获取旋转的弧度 速率达到一定程度 该方法 才会响应
    CGFloat rotation = sender.rotation;
    //让图片旋转
    self.imageView.transform = CGAffineTransformMakeRotation(rotation);
}
  • 变形
- (IBAction)clickButton:(id)sender {
    //将常量赋值给 transform属性,所有效果都会清除
    self.imageView.transform = CGAffineTransformIdentity;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    /****** 位移变化 ******************************/
    //带 Make 函数, 是基于变化前的位置,进行位移
//    self.imageView.transform = CGAffineTransformMakeTranslation(50, 50);
    //不带 Make 函数, 是基于每次变化基础上, 再进行位移
    self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, 50, 50);


    /****** 旋转变化 ******************************/
    //旋转时 会 旋转坐标系方向
//    self.imageView.transform = CGAffineTransformMakeRotation(M_PI_4);
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, M_PI_4);

     /****** 缩放变化 ******************************/
//    self.imageView.transform = CGAffineTransformMakeScale(1.5, 1.1);
    self.imageView.transform = CGAffineTransformScale(self.imageView.transform, 1.1, 1.1);

    NSLog(@"transform = %@",NSStringFromCGAffineTransform(self.imageView.transform));

}
  • 手势加变形
#import "ViewController.h"

@interface ViewController () <UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController
//手势的代理方法
//希望哪些手势共存就需要给这些手势添加代理
//所有手势可以公用父类的代理,只要遵守父类的代理协议就可以
//重写该代理方法,返回YES,那么设置代理的手势就可以同时响应
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(nonnull UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //1. pan 拖拽手势 控制图片 位移
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
    //2. pinch手势实现 缩放
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
    //设置代理
    pinch.delegate = self;
    [self.view addGestureRecognizer:pinch];
    //3. rotation手势实现 旋转
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotation:)];
    //设置代理
    rotation.delegate = self;
    [self.view addGestureRecognizer:rotation];
    //4. tap手势 取消所有 变形
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer:tap];
}
-(void)tap:(UITapGestureRecognizer*)sender {
    //取消所有变化
    self.imageView.transform = CGAffineTransformIdentity;
}
-(void)pan:(UIPanGestureRecognizer*)sender {
    //获取拖拽的位置
    CGPoint position = [sender translationInView:self.view];
    self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, position.x, position.y);
    //把手势中的 便宜量清 0
    [sender setTranslation:CGPointZero inView:self.view];
}
-(void)pinch:(UIPinchGestureRecognizer*)sender {
    CGFloat scale = sender.scale;
    self.imageView.transform = CGAffineTransformScale(self.imageView.transform, scale, scale);
    //把前一次 看成1个单位
    sender.scale = 1;
}
-(void)rotation:(UIRotationGestureRecognizer*)sender {
    //获取 手势旋转的弧度
    CGFloat rotate = sender.rotation;
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, rotate);
    sender.rotation = 0;
}

@end
  • 坐标系认证
- (IBAction)clickFrame:(id)sender {
    CGRect frame = self.imageview.frame;
    frame.origin.x += 10;
    frame.origin.y += 10;
    frame.size.width += 20;
    frame.size.height += 20;
    self.imageview.frame = frame;
    [self printInfo];
}
- (IBAction)clickBounds:(id)sender {
    CGRect bounds = self.imageview.bounds;
//    bounds.origin.x += 10;
//    bounds.origin.y += 10;
    bounds.size.width += 20;
    bounds.size.height += 20;
    self.imageview.bounds = bounds;
    [self printInfo];
}
- (IBAction)clickCenter:(id)sender {
    CGPoint center = self.imageview.center;
    center.x += 20;
    center.y += 20;
    self.imageview.center = center;
    [self printInfo];
}
- (IBAction)clickTransform:(id)sender {

//    self.imageview.transform = CGAffineTransformTranslate(self.imageview.transform, 30, 30);
//    self.imageview.transform = CGAffineTransformRotate(self.imageview.transform, M_PI_4);
    self.imageview.transform = CGAffineTransformScale(self.imageview.transform, 1.2, 1.5);

    [self printInfo];
}

-(void)printInfo {
    NSLog(@"\nframe:%@\nbounds:%@\ncenter:%@\ntransform:%@",
          NSStringFromCGRect(self.imageview.frame),
          NSStringFromCGRect(self.imageview.bounds),
          NSStringFromCGPoint(self.imageview.center),
          NSStringFromCGAffineTransform(self.imageview.transform));
    NSLog(@"-----------------------");

}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self printInfo];
}

5.0 UIImage动画

#import "ViewController.h"

#define FPS 5

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //直接使用 UIImage 创建动画  (不需要我们释放图片对象)
    UIImage *image = [UIImage animatedImageNamed:@"ship-anim" duration:1.0/FPS * 5];
    self.imageView.image = image;

    [self createImageViewAnimation:32 frameImageName:@"huxian" animateDuration:1.0/10 repeatCount:2];
}

-(void)createImageViewAnimation:(NSInteger)frameCount frameImageName:(NSString*)frameImageName animateDuration:(CGFloat)duration repeatCount:(NSInteger)repeatCount{
    //UIImageView动画
    //自己创建所需的 UIImage 让后通过 UIImageView来显示动画
    //创建保存动画 image 的数组
    NSMutableArray *allImage = [NSMutableArray array];
    //通过循环 创建UIImage实例(每一帧) 并且添加到数组中
    for (int i = 0; i < frameCount; i++) {
        //拼接每一帧的名字
        NSString *imageName = [NSString stringWithFormat:@"%@%02d.png",frameImageName, i+1];
        //创建UIImage实例
        UIImage *image = [UIImage imageNamed:imageName];
        //将UIImage实例添加到数组中
        [allImage addObject:image];
    }
    //设置imageview做动画所需的所以UIImage, 通过数组设置
    self.imageView.animationImages = allImage;


    //设置imageView做动画所需时间 (1次动画的时间)
    //  1/3  int 0
    //  1.0 / 3  float  0.3333333 (隐式类型转换)
    self.imageView.animationDuration = duration * frameCount;
    //设置动画执行次数 (0表示无限执行)
    self.imageView.animationRepeatCount = repeatCount;
    //开始动画
    [self.imageView startAnimating];

    //如果不是一直重复播放, 在播放完成时, 释放图片
    if (repeatCount != 0) {
        //动画结束时 释放掉图片
        //动画运行2次后,释放动画用的图片
        [self.imageView performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.imageView.animationDuration * repeatCount];
    }
}

@end

5.1 NSTimer定时器

@interface MyViewController()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation MyViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //开启定时器
    [NSTimer scheduledTimerWithTimeInterval:1/60.0 target:self selector:@selector(move:) userInfo:nil repeats:YES];
}

-(void)move:(NSTimer*)sender {
    //如果到达右边界就停止定时器
    if (self.imageView.center.x >= self.view.bounds.size.width - self.imageView.bounds.size.width ) {
        [sender invalidate]; // 停止定时器
        return;
    }

    CGPoint center = self.imageView.center;
    center.x += 5;
    self.imageView.center = center;
}

@end

5.2 UIView动画

- (void)viewDidLoad {
    [super viewDidLoad];
   //开始时 的 center  开始状态
    CGPoint center = self.imageView.center;
    self.imageView.alpha = 0;
    //计算结束时的 center
    center.x += 100;
    center.y += 400;

//    [UIView animateWithDuration:2 animations:^{
//        //设置 imageView 结束时的状态
//        self.imageView.center = center;
//        self.imageView.alpha = 1;
//    }];

    //参数 1:持续时间 2:等待多长时间开始执行动画 3.选项:动画线性速度 | 重复 | 回来动画  4.动画主体  5.动画执行完执行的Block
    [UIView animateWithDuration:2 delay:1 options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
        self.imageView.center = center;
        self.imageView.alpha = 1;
    } completion:nil];


}

5.3 UIView转场动画

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //options 只能选择带有 transition 的选项
    [UIView transitionWithView:self.imageView duration:2 options:UIViewAnimationOptionTransitionCurlUp animations:^{
        self.imageView.image = [UIImage imageNamed:@"welcome2"];
    } completion:nil];


    [UIView transitionWithView:self.myView duration:2 options:UIViewAnimationOptionTransitionCurlUp animations:^{
        self.myView.backgroundColor = [UIColor greenColor];
    } completion:nil];
}

5.4 CALayer

- (void)viewDidLoad {
    [super viewDidLoad];
    //获取 myView中的 CALayer属性
    CALayer *layer = self.myView.layer;
    layer.backgroundColor = [UIColor greenColor].CGColor;
    //设置圆角的半径
    layer.cornerRadius = 20;
    //设置边的颜色
    layer.borderColor = [UIColor redColor].CGColor;
    //设置边宽度
    layer.borderWidth = 3;

    //一定要设置   默认是0 透明 看不见
    layer.shadowOpacity = 1;
    //设置阴影边境
    layer.shadowRadius = 10;
    //设置阴影颜色
    layer.shadowColor = [UIColor blackColor].CGColor;
    //设置阴影的偏移量
    layer.shadowOffset = CGSizeMake(10, 10);

    //设置imageView中的layer
    self.imageView.layer.borderWidth = 3;
    self.imageView.layer.borderColor = [UIColor redColor].CGColor;
    self.imageView.layer.cornerRadius = self.imageView.bounds.size.width * 0.5  ;
    //当前层已经改变,但是上面有个图片,所以要按照层的边缘进行遮罩
    self.imageView.layer.masksToBounds = YES;


    //CALayer具有容器的特性,可以互相嵌套
    CALayer *myLayer = [CALayer layer];
    myLayer.backgroundColor = [UIColor redColor].CGColor;
    //设置大小
    myLayer.bounds = CGRectMake(0, 0, 40, 40);
    //设置 锚点 取值范围 0 ~ 1 自身的一个点 默认是0.5 0.5
    myLayer.anchorPoint = CGPointMake(0.5, 0.5);
    //设置位置 是自身在父layer中的 点
    myLayer.position = CGPointMake(100, 100);
    //旋转 和 缩放 都是依据锚点进行
    myLayer.transform = CATransform3DMakeRotation(M_PI_4, 0, 0, 1);

    //将自定义的layer 添加到 myView的layer 上
    [self.myView.layer addSublayer:myLayer];

}
#import "ViewController.h"

//宏 纯文本替换
#define AngleToRadian(x) (x)/180.0*M_PI



@interface ViewController ()
@property(nonatomic,strong)UIImageView *imageView;
//定时器
@property(nonatomic,strong)CADisplayLink *link;
@end

@implementation ViewController


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.link.paused = !self.link.paused;
}

//不能定时的 定时器   一秒钟最好的情况 执行 60次,每刷新一次执行一次
-(CADisplayLink *)link {
    if (!_link) {
        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(rotation:)];
        //把定时器 添加到 主循环队列中
        [_link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        //设置 开始时 不运行
        _link.paused = YES;
    }
    return _link;
}

-(void)rotation:(CADisplayLink*)sender {
    self.imageView.layer.transform = CATransform3DRotate(self.imageView.layer.transform, AngleToRadian(72 / 60.0), 0, 0, 1);
}


- (void)viewDidLoad {
    [super viewDidLoad];

    CGSize viewSize = self.view.bounds.size;

    self.imageView = [[UIImageView alloc]init];
    self.imageView.image = [UIImage imageNamed:@"bg"];
    self.imageView.layer.bounds = CGRectMake(0, 0, viewSize.width - 40, viewSize.width - 40);
    self.imageView.layer.position = CGPointMake(viewSize.width * 0.5, viewSize.height * 0.5);
    //默认也是 0.5  0.5
//    self.imageView.layer.anchorPoint = CGPointMake(1, 1);
    //设置圆角半径
    self.imageView.layer.cornerRadius = self.imageView.bounds.size.width * 0.5;
    //进行遮罩
    self.imageView.layer.masksToBounds = YES;
    [self.view addSubview:self.imageView];

    for (int i = 0; i < 8; i++) {
        CALayer *layer = [CALayer layer];
        //为层添加图像内容
        layer.contents = (id)[UIImage imageNamed:@"bg"].CGImage;

        layer.bounds = CGRectMake(0, 0, 10, self.imageView.bounds.size.width * 0.5);
        layer.anchorPoint = CGPointMake(0.5,1);
        layer.position = CGPointMake(self.imageView.bounds.size.width * 0.5, self.imageView.bounds.size.height * 0.5);

        //旋转
        layer.transform = CATransform3DMakeRotation(M_PI_4 * i, 0, 0, 1);

        [self.imageView.layer addSublayer:layer];
    }
}

@end
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建文字类型的图层
    CATextLayer *tlayer = [CATextLayer layer];
    tlayer.string = @"文字图层";
    tlayer.fontSize = 36;
    tlayer.foregroundColor = [UIColor greenColor].CGColor;
    tlayer.bounds = CGRectMake(0, 0, 200, 60);
    tlayer.position = CGPointMake(50, 150);
    tlayer.anchorPoint = CGPointMake(0, 0);
    tlayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:tlayer];


    //创建图形层
    CAShapeLayer *slayer = [CAShapeLayer layer];
    slayer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 10, 100, 50) cornerRadius:15].CGPath;
    slayer.strokeColor = [UIColor redColor].CGColor;
    slayer.fillColor = [UIColor blueColor].CGColor;

    slayer.position = CGPointMake(50, 250);
    slayer.anchorPoint = CGPointZero;
    [self.view.layer addSublayer:slayer];
}

5.5 手动布局

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;

@end

@implementation ViewController

//重写父类方法  隐藏状态栏
-(BOOL)prefersStatusBarHidden {
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.navigationController setNavigationBarHidden:!self.navigationController.navigationBarHidden animated:YES];
    //导航发生变化重新布局
    CGFloat y = self.topLayoutGuide.length + 20;
    CGRect frame = CGRectMake(self.view.bounds.size.width - self.button1.bounds.size.width - 20, y, self.button1.bounds.size.width, self.button1.bounds.size.height);
    self.button1.frame = frame;

    //如果底部有bar,就是底部bar的高度,如果没有 0;
//    self.bottomLayoutGuide.length;

}

//此方式 在屏幕内容从无到有时 会自动调用
//屏幕旋转时 会 自动调用
-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    //设置第一个button 在 self.view 的右上
    //self.topLayoutGuide.length 顶部内容的高度
    CGFloat y = self.topLayoutGuide.length + 20;
    CGRect frame = CGRectMake(self.view.bounds.size.width - self.button1.bounds.size.width - 20, y, self.button1.bounds.size.width, self.button1.bounds.size.height);
    self.button1.frame = frame;

    frame = CGRectMake(20, self.view.bounds.size.height - self.button2.bounds.size.height - 20, self.button2.bounds.size.width, self.button2.bounds.size.height);
    self.button2.frame = frame;
}

@end

5.6 Masonry

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview:view];

    UIView *view2 = [UIView new];
    view2.backgroundColor = [UIColor greenColor];
    [self.view addSubview:view2];

    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 100));
//        make.left.mas_equalTo(20);
//        make.top.mas_equalTo(20);
        make.left.and.top.mas_equalTo(20);
    }];

    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 100));
        make.top.mas_equalTo(view);
        make.right.mas_equalTo(-20);
    }];


    [view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 200));
    }];


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值