UI学习2

张开发
2026/4/13 9:06:08 15 分钟阅读

分享文章

UI学习2
UI学习2定时器和视图移动NSTimer是Foundation框架提供的定时器可以在指定时间间隔后执行某个方法。通过定时器我们可以让视图连续移动实现简单的动画效果。我们先定义一个定时器对象#importUIKit/UIKit.hinterfaceViewController:UIViewController{NSTimer*time;}property(retain,nonatomic)NSTimer*timeView;end#importViewController.hinterfaceViewController()endimplementationViewControllersynthesizetimeViewtime;-(void)viewDidLoad{[superviewDidLoad];// 创建“启动定时器”按钮UIButton*button[UIButton buttonWithType:UIButtonTypeRoundedRect];button.frameCGRectMake(100,100,100,100);[button setTitle:启动定时器forState:UIControlStateNormal];[button addTarget:selfaction:selector(pressStart)forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:button];// 创建“停止定时器”按钮UIButton*buttonStop[UIButton buttonWithType:UIButtonTypeRoundedRect];buttonStop.frameCGRectMake(100,200,100,100);[buttonStop setTitle:停止定时器forState:UIControlStateNormal];[buttonStop addTarget:selfaction:selector(pressStop)forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:buttonStop];// 创建一个蓝色方块设置初始位置和大小UIView*view[[UIView alloc]init];view.frameCGRectMake(0,0,80,80);// 初始位置 (0,0)view.backgroundColor[UIColor blueColor];[self.view addSubview:view];view.tag101;// 设置标签便于在定时器回调中获取该视图}// 启动定时器的方法-(void)pressStart{// 如果定时器已经存在先停止并释放if(time!nil){[time invalidate];timenil;}// 创建并启动一个重复定时器每 0.1 秒调用 updateTimer: 方法// 注意必须将定时器赋值给 time 变量否则 pressStop 无法停止time[NSTimer scheduledTimerWithTimeInterval:0.1target:selfselector:selector(updateTimer:)userInfo:小明repeats:YES];}// 定时器回调方法-(void)updateTimer:(NSTimer*)timer{// 打印 userInfo 中的信息NSLog(% test,timer.userInfo);// 通过 tag 获取之前创建的蓝色方块UIView*view[self.view viewWithTag:101];// 每次移动视图的 origin 向右下各增加 1 点view.frameCGRectMake(view.frame.origin.x1,view.frame.origin.y1,80,80);}// 停止定时器的方法-(void)pressStop{if(time!nil){[time invalidate];// 停止定时器timenil;// 清空指针防止野指针}}endscheduledTimerWithTimeInterval:0.1表示每隔 0.1 秒触发一次。target:self指定回调方法所在的对象。selector:selector(updateTimer:)时间到了就调用updateTimer:方法。userInfo:小明可以携带额外信息回调里通过timer.userInfo取出。repeats:YES表示重复执行否则只执行一次。invalidate让定时器失效并且要把指针清空避免再次调用时出现野指针。UISwitchUISwitch常用于开/关状态常用于设置选项#importUIKit/UIKit.hinterfaceViewController:UIViewController{UISwitch*_switch;}property(retain,nonatomic)UISwitch*mySwitch;end#importViewController.hinterfaceViewController()endimplementationViewControllersynthesizemySwitch_switch;-(void)viewDidLoad{[superviewDidLoad];// 创建 UISwitch 开关控件_switch[[UISwitch alloc]init];// 设置开关的位置大小固定只有 origin 有效width/height 被忽略_switch.frameCGRectMake(100,100,80,40);// 设置开关的背景颜色_switch.backgroundColor[UIColor redColor];// 设置开关初始状态为开启_switch.onYES;// 重复设置 on 状态无额外效果[_switch setOn:YES];// 带动画地设置开关状态这里再次设为 YES因为已经是 YES动画无变化[_switch setOn:YES animated:YES];// 将开关添加到当前视图[self.view addSubview:_switch];// 设置开关开启时的轨道颜色蓝色[_switch setOnTintColor:[UIColor blueColor]];// 设置开关滑块的颜色红色[_switch setThumbTintColor:[UIColor redColor]];// 为开关添加事件值改变时调用 swChange: 方法[_switch addTarget:selfaction:selector(swChange:)forControlEvents:UIControlEventValueChanged];// 创建 UILabel 标签UILabel*label[[UILabel alloc]init];label.text张璐阳控制器;label.font[UIFont systemFontOfSize:16];// 设置标签位置和大小x100, y110, width100, height200label.frameCGRectMake(100,110,100,200);label.textColor[UIColor greenColor];[self.view addSubview:label];}// 开关状态改变时调用的方法-(void)swChange:(UISwitch*)sw{if(sw.onYES){NSLog(已打开);}elseif(sw.onNO){NSLog(已关闭);}}end虽然frame可以设置位置但开关的尺寸是系统固定的宽高设置会被忽略。addTarget:action:forControlEvents:监听值改变事件当用户拨动开关时就会调用swChange:方法。通过sw.on获取当前开关状态做对应的逻辑处理。UISlider和UIprogressViewUISlider允许用户在最小值和最大值之间选择一个值常用于音量、亮度调节等,UIProgressView用于显示任务完成进度如下载进度、播放进度等。#importUIKit/UIKit.hinterfaceViewController:UIViewController{UIProgressView*pro;UISlider*sli;}property(retain,nonatomic)UIProgressView*Pro;property(retain,nonatomic)UISlider*Sli;end#importViewController.himplementationViewController-(void)viewDidLoad{[superviewDidLoad];// 创建进度条 UIProgressViewpro[[UIProgressView alloc]init];// 设置进度条的位置和大小x100, y100, width200, height40但高度固定实际只有约2~4点pro.frameCGRectMake(100,100,200,40);// 设置进度条已完成部分的颜色红色pro.progressTintColor[UIColor redColor];// 设置进度条未完成部分的颜色黑色pro.trackTintColor[UIColor blackColor];// 设置初始进度为 0.550%pro.progress0.5;// 设置进度条样式默认样式pro.progressViewStyleUIProgressViewStyleDefault;// 将进度条添加到当前视图[self.view addSubview:pro];// 创建滑动条 UISlidersli[[UISlider alloc]init];// 设置滑动条的位置和大小x40, y100, width300, height40sli.frameCGRectMake(40,100,300,40);// 设置滑动条的最大值100sli.maximumValue100;// 设置滑动条的最小值0sli.minimumValue0;// 设置滑动条的初始值50sli.value50;// 设置滑动条左侧最小值一侧轨道的颜色蓝色sli.minimumTrackTintColor[UIColor blueColor];// 设置滑动条右侧最大值一侧轨道的颜色绿色sli.maximumTrackTintColor[UIColor greenColor];// 设置滑块圆形按钮的颜色橙色sli.thumbTintColor[UIColor orangeColor];// 为滑动条添加事件监听值改变时调用 presssli 方法[sli addTarget:selfaction:selector(presssli)forControlEvents:UIControlEventValueChanged];// 将滑动条添加到当前视图[self.view addSubview:sli];}// 滑动条值改变时调用的方法-(void)presssli{// 根据滑动条的当前值计算进度归一化到 0~1 范围pro.progress(sli.value-sli.minimumValue)/(sli.maximumValue-sli.minimumValue);// 打印当前滑动条的值NSLog(位置在%f,sli.value);}endminimumValue/maximumValue决定了滑动条的数值范围。值改变时触发presssli方法。等待指示器和警告对话框#import UIKit/UIKit.h interface ViewController : UIViewController { UIAlertController* _alertView; UIActivityIndicatorView* _activityIndicator; } property (retain, nonatomic) UIAlertController* alertView; property (retain, nonatomic) UIActivityIndicatorView* activityIndicator; end#importViewController.h// 类扩展用于声明私有属性原代码未展示但实际需要interfaceViewController()// 注意实际使用前应在 interface 中声明 _alertView 和 _activityIndicator// 例如// property (nonatomic, strong) UIAlertController *alertView;// property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;endimplementationViewController-(void)viewDidLoad{[superviewDidLoad];// Do any additional setup after loading the view.// 循环创建两个按钮for(inti0;i2;i){// 创建圆角矩形按钮UIButton*btn[UIButton buttonWithType:UIButtonTypeRoundedRect];// 设置按钮位置x100, y 从 100 开始每个按钮间隔 100 点btn.frameCGRectMake(100,100100*i,100,40);// 根据循环索引设置按钮标题if(i0){[btn setTitle:提示对话框forState:UIControlStateNormal];}elseif(i1){[btn setTitle:等待forState:UIControlStateNormal];}// 设置按钮标签方便在点击方法中区分不同按钮btn.tag101i;// 添加点击事件监听[btn addTarget:selfaction:selector(pressBtn:)forControlEvents:UIControlEventTouchUpInside];// 将按钮添加到当前视图[self.view addSubview:btn];}}// 按钮点击回调方法-(void)pressBtn:(UIButton*)btn{// 根据按钮标签执行不同操作if(btn.tag101){// 创建警告框控制器UIAlertController样式为弹窗Alert_alertView[UIAlertController alertControllerWithTitle:警告message:手机电量过低preferredStyle:UIAlertControllerStyleAlert];// 创建“取消”动作样式为取消样式点击后不做额外处理handler 为 nilUIAlertAction*cancle[UIAlertAction actionWithTitle:取消style:UIAlertActionStyleCancel handler:nil];[_alertView addAction:cancle];// 创建“新的”动作样式为默认样式点击后也不做处理UIAlertAction*newAction[UIAlertAction actionWithTitle:新的style:UIAlertActionStyleDefault handler:nil];[_alertView addAction:newAction];// 创建“确认”动作并添加一个 block 回调点击时输出日志UIAlertAction*confirm[UIAlertAction actionWithTitle:确认style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnull action){NSLog(确认);}];[_alertView addAction:confirm];// 以模态方式显示警告框[selfpresentViewController:_alertView animated:YES completion:nil];}elseif(btn.tag102){// 创建活动指示器菊花转圈并设置其位置和大小_activityIndicator[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(157,300,100,100)];// 设置指示器样式为大号白色_activityIndicator.activityIndicatorViewStyleUIActivityIndicatorViewStyleLarge;// 将指示器添加到当前视图[self.view addSubview:_activityIndicator];// 开始动画旋转显示[_activityIndicator startAnimating];}}endUIAlertController使用alertControllerWithTitle:message:preferredStyle:创建样式有UIAlertControllerStyleAlert弹窗和ActionSheet底部上滑。UIAlertAction代表一个按钮可以设置标题、样式和点击后的回调handler。presentViewController:animated:completion:显示对话框。UIActivityIndicatorView创建后设置样式UIActivityIndicatorViewStyleLarge为大号调用startAnimating开始旋转stopAnimating停止。生命周期init/initWithCoder:调用时机控制器通过代码或 Storyboard/XIB 创建时。作用执行最基本的初始化此时视图尚未加载。注意一般不在这里操作界面相关的属性因为视图还未存在。loadView调用时机当控制器的view被访问但为nil时调用。作用创建控制器的根视图。如果使用 Storyboard 或 XIB通常不需要重写此方法纯代码方式可以在这里自定义根视图。注意不要手动调用此方法。如果重写必须自己创建self.view并且不要调用[super loadView]。viewDidLoad调用时机视图加载完成后调用只调用一次。作用进行界面初始化、添加子视图、加载数据、设置通知等。注意此时视图的frame可能还未最终确定因为布局尚未计算不要在这里依赖视图的尺寸进行精细布局。-(void)viewDidLoad{[superviewDidLoad];// 添加子视图、设置初始数据self.view.backgroundColor[UIColor whiteColor];UIButton*btn[UIButton buttonWithType:UIButtonTypeSystem];btn.frameCGRectMake(100,100,100,40);[btn setTitle:点我forState:UIControlStateNormal];[self.view addSubview:btn];}viewWillAppear:调用时机视图即将添加到视图层级上并显示在屏幕上时调用每次出现都会调用。作用执行每次显示前需要做的操作比如更新数据、刷新界面、注册键盘通知等。参数animated表示是否有动画。viewDidAppear:调用时机视图已经完全显示在屏幕上后调用每次出现都会调用。作用开始动画、启动定时器、发起网络请求等。用户已经看到界面适合做需要可见后才执行的操作。viewWillDisappear:调用时机视图即将从视图层级中移除即将被遮盖或关闭时调用。作用保存用户输入、停止正在进行的任务、释放临时资源等。viewDidDisappear:调用时机视图已经从视图层级中移除后调用。作用停止动画、移除通知、清理不需要的资源。didReceiveMemoryWarning调用时机系统内存紧张时调用。作用释放可重建的资源如缓存图片、未显示的视图等。如果控制器有不再需要的视图系统会自动将view设为nil。-(void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];// 清理缓存等可重建的资源}dealloc调用时机控制器被释放时调用。作用清理通知、定时器、代理等避免内存泄漏。-(void)dealloc{[[NSNotificationCenter defaultCenter]removeObserver:self];[timer invalidate];timernil;}

更多文章