目录
UISwitch
UISwitch是一个开关控件,可以进行状态的改变(两种状态:开 | 关)
@interface ViewController : UIViewController
//所有UIKit框架库中的控件均以UI开头
//🍎官方的控件都定义在UIKit框架库中
@property (retain, nonatomic)UISwitch* mySwitch;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建一个开关对象
//继承于UIView
self.mySwitch = [[UISwitch alloc] init];
//苹果官方的控件的位置设置
//位置X,Y的值可以改变
//宽度和高度值无法改变
self.mySwitch.frame = CGRectMake(100, 200, 180, 40);
//_mySwitch.backgroundColor = [UIColor orangeColor];
//开关状态设置
//YES:开启状态
//NO:关闭状态
self.mySwitch.on = YES;
//也可以使用set函数
[_mySwitch setOn: YES];
//设置开关状态
//P1:状态设置
//P2:是否开启动画效果
[self.mySwitch setOn: YES animated: YES];
[self.view addSubview: self.mySwitch];
//设置开启状态的风格颜色
[self.mySwitch setOnTintColor: [UIColor purpleColor]];
//设置开关圆按钮的风格颜色
[self.mySwitch setThumbTintColor: [UIColor systemPinkColor]];
//设置整体风格颜色
[self.mySwitch setTintColor: [UIColor blueColor]];
//self.view.backgroundColor = [UIColor magentaColor];
//向开关控件添加事件函数
//P1:函数实现对象
//P2:函数对象
//P3:事件响应时的事件类型UIControlEventValueChanged: 状态发生变化时触发函数
[self.mySwitch addTarget: self action: @selector(swChange:) forControlEvents: UIControlEventValueChanged];
}
//参数传入开关对象本身
- (void)swChange: (UISwitch*)sw {
//on表示当前最终结束的状态
if (sw.on == YES) {
NSLog(@"开关被打开!");
} else {
NSLog(@"开关被关闭!");
}
NSLog(@"开关状态发生变化!");
}
@end
UISlider&UIProgressView
UISlider为滑动条,一般用来进行调整音乐的音量等。
UIProgressView为进度条,一般用来表示下载或视频播放的进度。
@interface ViewController : UIViewController
//定义一个进度条属性
@property (retain, nonatomic)UIProgressView* pView;
//定义一个滑动条属性
@property (retain, nonatomic)UISlider* slider;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//进度条的创建
self.progressView = [[UIProgressView alloc] init];
//进度条的位置
//进度条的高度是不可变化的
self.progressView.frame = CGRectMake(100, 100, 200, 40);
//设置进度条的风格颜色
//默认是蓝色
self.progressView.progressTintColor = [UIColor systemYellowColor];
self.progressView.trackTintColor = [UIColor darkGrayColor];
//设置进度条的进度值
//范围0~1,最小值为0,最大值为1
self.progressView.progress = 0.7;
//设置进度条的风格特征
self.progressView.progressViewStyle = UIProgressViewStyleDefault;
[self.view addSubview: self.progressView];
//创建滑动条对象
self.slider = [[UISlider alloc] init];
//滑动条的位置
//滑动条的高度是不可变化的
self.slider.frame = CGRectMake(10, 200, 200, 80);
//设置滑动条最大值
self.slider.maximumValue = 100;
//设置滑动条最小值,可以为负值
self.slider.minimumValue = -100;
//设置滑动条的滑块的位置float值
self.slider.value = 0;
//左侧滑条背景颜色,默认蓝色
self.slider.minimumTrackTintColor = [UIColor systemBlueColor];
//右侧滑条背景颜色,默认灰色
self.slider.maximumTrackTintColor = [UIColor lightGrayColor];
//设置滑块的颜色
self.slider.thumbTintColor = [UIColor systemMintColor];
//对滑动条添加事件函数
[self.slider addTarget: self action: @selector(pressSlider) forControlEvents: UIControlEventValueChanged];
[self.view addSubview: self.slider];
}
- (void)pressSlider {
//范围都在0~1的情况下,赋给进度条的进度值
//self.progressView.progress = self.slider.value;
//若范围不在0~1,运用以下算法
self.progressView.progress = (self.slider.value - self.slider.minimumValue) / (self.slider.maximumValue - self.slider.minimumValue);
NSLog(@"value = %f", self.slider.value);
}
@end
视图控制器的使用
此小节会介绍一些ViewController的响应函数。
ViewController.m
@implementation ViewController
//当屏幕被点击时,调用此函数
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//创建视图控制器02
ViewC02* vc = [[ViewC02 alloc] init];
//显示一个新的视图控制器在屏幕上
//P1:新的视图控制器对象
//P2:使用动画切换动画效果
//P3:切换结束后功能调用,不需要传nil值即可
vc.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController: vc animated: YES completion: nil];
}
//第一次程序加载视图时调用
//只会加载一次
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor blueColor];
NSLog(@"viewDidLoad!第一次加载视图!");
}
//当视图控制器的视图即将显示时,调用此函数
//视图分为:1.显示前(不显示) 2.正在显示状态 3.已经被隐藏
//参数:表示是否用动画切换后显示
//每一次视图显示时都要被调用
- (void)viewWillAppear: (BOOL)animated {
NSLog(@"viewWillAppear,视图即将显示!");
}
//视图即将消失时,调用此函数
//参数:表示是否用动画切换后消失
//当前的状态:视图还是显示在屏幕上的
- (void)viewWillDisappear: (BOOL)animated {
NSLog(@"viewWillDisappear,视图即将消失!");
}
//当视图已经显示到屏幕后瞬间调用此函数
//参数:表示是否用动画切换显示
//当前状态已经显示到屏幕上了
- (void)viewDidAppear: (BOOL)animated {
NSLog(@"viewDidAppear,视图已经显示!");
}
//当前视图已经从屏幕上消失
//参数:表示是否用动画切换显示
//当前状态控制视图已经从屏幕上消失
- (void)viewDidDisappear: (BOOL)animated {
NSLog(@"viewDidDisappear,视图已经消失!");
}
@end
ViewC02.m
@implementation ViewC02
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//控制器02的颜色为橙色
self.view.backgroundColor = [UIColor orangeColor];
}
//点击当前控制器02的界面屏幕时
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//使当前的控制器消失掉
//P1:是否有动画效果
//P2:结束后是否调用功能block块操作
[self dismissViewControllerAnimated: YES completion: nil];
}
//- (void)viewWillAppear: (BOOL)animated {
// NSLog(@"viewWillAppear,视图02即将显示!");
//}
//
//- (void)viewWillDisappear: (BOOL)animated {
// NSLog(@"viewWillDisappear,视图02即将消失!");
//}
//
//- (void)viewDidAppear: (BOOL)animated {
// NSLog(@"viewDidAppear,视图02已经显示!");
//}
//
//- (void)viewDidDisappear: (BOOL)animated {
// NSLog(@"viewDidDisappear,视图02已经消失!");
//}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
定时器和视图对象
定时器可以在每个固定时间发送一个消息,通过此消息来调用相应的事件函数,通过此函数可在固定时间段来完成一个根据时间间隔的任务。
@interface ViewController : UIViewController
//定时器的属性对象
@property (retain, nonatomic)NSTimer* timerView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//启动定时器按钮
UIButton* btn = [UIButton buttonWithType: UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 80, 40);
[btn setTitle: @"启动定时器" forState: UIControlStateNormal];
[btn addTarget: self action: @selector(pressStart) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview: btn];
//停止定时器按钮
UIButton* btnStop = [UIButton buttonWithType: UIButtonTypeRoundedRect];
btnStop.frame = CGRectMake(100, 200, 80, 40);
[btnStop setTitle: @"停止定时器" forState: UIControlStateNormal];
[btnStop addTarget: self action: @selector(pressStop) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview: btnStop];
UIView* view = [[UIView alloc] init];
view.frame = CGRectMake(0, 0, 80, 80);
view.backgroundColor = [UIColor orangeColor];
//view.alpha = 0.5;
[self.view addSubview: view];
//设置view的标签值
//通过父亲视图对象以及view的标签值可以获得相应的视图对象
view.tag = 101;
}
//按下开始按钮函数
- (void)pressStart {
//NSTimer的类方法创建一个定时器并且启动这个定时器
//P1:每隔多长时间调用定时器函数,以秒为单位
//P2:表示实现定时器函数的对象(指针)
//P3:定时器函数对象
//P4:可以传入定时器函数中的一个参数,无参数可以传nil
//P5:定时器是否重复操作,YES为重复,NO只完成一次函数调用
//返回值为一个新建好的定时器对象
if (!_timerView) {
_timerView = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(updateTimer:) userInfo: @"小明" repeats: YES];
}
}
//定时器函数
//可以将定时器本身作为参数传入
- (void)updateTimer: (NSTimer*)timer {
//userInfo是id类型
NSLog(@"test!!! name = %@", timer.userInfo);
//最好tag从100开始
//创建一个UIView
UIView* view = [self.view viewWithTag: 101];
view.frame = CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, 80, 80);
}
//按下停止按钮时调用
- (void)pressStop {
if (_timerView) {
//停止定时器
[_timerView invalidate];
//NSLog(@"%@", _timerView);
_timerView = nil;
}
}
@end
步进器和分栏控件
步进器、分栏控制器都可以按照一定的数值来调整某个数据。
@interface ViewController : UIViewController
//属性定义
@property (retain, nonatomic)UIStepper* stepper;
@property (retain, nonatomic)UISegmentedControl* segControl;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建步进器对象
self.stepper = [[UIStepper alloc] init];
//设置位置,宽高不能变更
self.stepper.frame = CGRectMake(100, 100, 80, 40);
//设置步进器的最小值
self.stepper.minimumValue = 0;
//设置步进器的最大值
self.stepper.maximumValue = 100;
//设置步进器的当前值,默认值为0
self.stepper.value = 10;
//设置步进值,每次向前或向后步进的步伐值
self.stepper.stepValue = 1;
//是否可以重复响应事件操作
//自动重复功能,YES可以通过长按持续改变状态
self.stepper.autorepeat = YES;
//是否将步进结果通过事件函数响应出来
self.stepper.continuous = YES;
//添加事件函数
//P1:实现函数体
//P2:函数体
//P3:事件值改变状态
[self.stepper addTarget: self action: @selector(stepChange) forControlEvents: UIControlEventValueChanged];
[self.view addSubview: self.stepper];
//创建分栏控件
self.segControl = [[UISegmentedControl alloc] init];
//设置控件位置,宽度可变,高度不可变
self.segControl.frame = CGRectMake(10, 200, 350, 40);
//添加一个按钮元素
//P1:按钮选项文字
//P2:按钮的索引位置
//P3:是否有插入的动画效果
[self.segControl insertSegmentWithTitle: @"0元" atIndex: 0 animated: YES];
[self.segControl insertSegmentWithTitle: @"5元" atIndex: 1 animated: YES];
[self.segControl insertSegmentWithTitle: @"10元" atIndex: 2 animated: YES];
[self.segControl insertSegmentWithTitle: @"30元" atIndex: 0 animated: YES];
//当前默认按钮索引设置
self.segControl.selectedSegmentIndex = 0;
[self.segControl addTarget: self action: @selector(segChange) forControlEvents: UIControlEventValueChanged];
[self.view addSubview: self.segControl];
}
- (void)segChange {
NSLog(@"%ld", (long)self.segControl.selectedSegmentIndex);
}
- (void)stepChange {
NSLog(@"step press! value = %f", self.stepper.value);
}
@end
警告对话框和等待提示器
UIAlertController
UIActivityIndicatorView
@interface ViewController : UIViewController <UIAlertViewDelegate>
@property (retain, nonatomic) UIAlertController* alertView;
@property (retain, nonatomic) UIActivityIndicatorView* activityIndicator;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
for (int i = 0; i < 2; ++i) {
UIButton* btn = [UIButton buttonWithType: UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100 + 100 * i, 100, 40);
if (i == 0) {
[btn setTitle: @"警告对话框" forState: UIControlStateNormal];
} else if (i == 1) {
[btn setTitle: @"等待指示器" forState: UIControlStateNormal];
}
//方便button事件的使用
btn.tag = 101 + i;
[btn addTarget: self action: @selector(pressBtn:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview: btn];
}
}
- (void)pressBtn: (UIButton*)btn {
//警告对话框创建
if (btn.tag == 101) {
//创建警告对话框
///P1:对话框标题
///P2:提示信息
//P3:处理按钮事件的代理对象
//P4:取消按钮的文字
//P5:其他按钮文字
//P6....:添加其他按钮
//PLast:表示按钮添加结束
self.alertView = [UIAlertController alertControllerWithTitle: @"警告" message: @"本机已被入侵,速速打钱!" preferredStyle: UIAlertControllerStyleAlert];
//选项一、二、三
UIAlertAction* sure = [UIAlertAction actionWithTitle: @"✅" style: UIAlertActionStyleDefault handler: ^(UIAlertAction * _Nonnull action) {
NSLog(@"✅确定");
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle: @"😜" style: UIAlertActionStyleCancel handler: nil];
UIAlertAction* weird = [UIAlertAction actionWithTitle: @"😂" style: UIAlertActionStyleDefault handler: ^(UIAlertAction * _Nonnull action) {
NSLog(@"搞怪");
}];
//添加选项到视图_alertView
[self.alertView addAction: sure];
[self.alertView addAction: cancel];
[self.alertView addAction: weird];
//显示对话框
[self presentViewController: self.alertView animated: YES completion: nil];
//创建等待提示器
} else if (btn.tag == 102) {
//宽高不可变
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame: CGRectMake(100, 300, 80, 80)];
//设定提示的风格:小灰,小白,大白
//self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; deprecated
self.view.backgroundColor = [UIColor magentaColor];
[self.view addSubview: self.activityIndicator];
//启动动画并显示
[self.activityIndicator startAnimating];
//停止等待动画并隐藏
//[self.activityIndicator stopAnimating];
}
}
//当点击对话框的按钮时,调用此函数
//P1:对话框对象本身
//P2:按钮的索引
//- (void)alertView: (UIAlertView*)alertView clickedButtonAtIndex: (NSInteger)buttonIndex {
// NSLog(@"index = %ld\n", buttonIndex);
//}
对话框即将消失,此函数被调用
//- (void)alertView: (UIAlertView*)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex {
// NSLog(@"即将消失!");
//}
对话框已经消失时,调用此函数
//- (void)alertView: (UIAlertView*)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
// NSLog(@"已经消失!");
//}
@end
UITextField
文本输入区域,可进行文本输入,例如,用户名、密码等需要输入文本文字的内容区域。
点击框内可调出虚拟键盘。
只能输入单行文字,不能输入或显示多行。
是UIControl的子类,UIControl是UIView的子类,如:frame
@interface ViewController : UIViewController
@property (retain, nonatomic)UITextField* textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//_textField
//创建一个文本输入区对象
self.textField = [[UITextField alloc]init];
//设定文本输入区的位置
self.textField.frame = CGRectMake(100, 200, 200, 40);
//设置textField的内容文字
self.textField.text = @"Mckenna";
//设置文字的字体大小
self.textField.font = [UIFont systemFontOfSize: 19];
//设置字体的颜色
self.textField.textColor = [UIColor orangeColor];
//设置边框的风格
//UITextBorderStyleRoundedRect:圆角风格
//UITextBorderStyleLine:线框风格
//UITextBorderStyleBezel:bezel线框风格
//UITextBorderStyleNone:无边框风格
self.textField.borderStyle = UITextBorderStyleLine;
//设置虚拟键盘风格⌨️
//UIKeyboardTypeDefalut:默认风格
//UIKryboardTypeNamePhonePad:字母和数字组合风格
//UIKeyboardTypeNumber:纯数字风格
self.textField.keyboardType = UIKeyboardTypeDefault;
//提示文字信息
//当text属性为空,显示此条信息
//浅灰色提示文字
self.textField.placeholder = @"请输入用户名.....😊";
//是否作为密码输入
//YES:圆点加密,隐式输入
//NO:正常显示输入的文字
self.textField.secureTextEntry = NO;
[self.view addSubview: self.textField];
//设置代理对象
//self.textField.delegate = self;
}
- (void)textFieldDidBeginEditing: (UITextField *)textField
{
NSLog(@"开始编辑了!");
}
- (void)textFieldDidEndEditing: (UITextField *)textField
{
self.textField.text = @"";
NSLog(@"编辑输入结束!");
}
//是否可以进行输入
//默认为YES
- (BOOL)textFieldShouldBeginEditing: (UITextField *)textField
{
return YES;
}
//是否可以结束输入
//默认为YES
- (BOOL)textFieldShouldEndEditing: (UITextField *)textField
{
return YES;
}
//点击屏幕空白处调用此函数
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//使虚拟键盘回收,不再作为第一消息响应者
[self.textField resignFirstResponder];
}
@end
导航控制器
导航控制器只要用来管理多个视图控制器的切换,层级的方式来管理多个视图控制器,创建控制器时,一定要有一个根视图控制器。
SceneDelegate.m
@implementation SceneDelegate
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
UIWindowScene* windowScene = (UIWindowScene *)scene;
self.window = [[UIWindow alloc] initWithWindowScene: windowScene];
self.window.frame = windowScene.coordinateSpace.bounds;
//创建一个根视图控制器
VCRoot* root = [[VCRoot alloc] init];
//创建导航控制器
//参数一:就是作为导航控制器的根视图控制器
UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController: root];
//将window的根视图作为导航控制器
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
}
VCRoot.m
@implementation VCRoot
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor orangeColor];
//设置导航栏的标题文字
self.title = @"根视图";
//设置导航元素项目的标题
//如果没有设置navigationItem.title,为nil,系统会使用self.title作为标题
//如果navigationItem.title不为空,将navigationItem.title设置为标题内容
self.navigationItem.title = @"Title";
//创建一个导航栏左侧按钮
//根据title文字来创建按钮
//P1:按钮上的文字
//P2:按钮风格
//P3:事件拥有者
//P4:按钮事件
UIBarButtonItem* leftBtn = [[UIBarButtonItem alloc] initWithTitle: @"🫲" style: UIBarButtonItemStyleDone target: self action: @selector (pressLeft)];
self.navigationItem.leftBarButtonItem = leftBtn;
//创建一个导航栏左侧按钮
//根据系统风格来创建按钮
//P1:按钮风格
//P2:事件拥有者
//P3:按钮事件
UIBarButtonItem* rightBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemBookmarks target: self action: @selector(pressRight)];
self.navigationItem.rightBarButtonItem = rightBtn;
//标签对象
UILabel* label = [[UILabel alloc] initWithFrame: CGRectMake(10, 10, 50, 40)];
label.text = @"test";
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor lightTextColor];
//将任何类型的控件添加到导航按钮的方法
UIBarButtonItem* item03 = [[UIBarButtonItem alloc] initWithCustomView: label];
//创建按钮数组
NSArray* arrayBtn = [NSArray arrayWithObjects: rightBtn, item03, nil];
//将右侧按钮数组赋值
self.navigationItem.rightBarButtonItems = arrayBtn;
}
- (void)pressLeft
{
NSLog(@"左侧按钮被按下!");
}
- (void)pressRight
{
NSLog(@"右侧按钮被按下");
}
导航栏和工具栏
SceneDelegate.m
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
UIWindowScene* windowScene = (UIWindowScene *)scene;
self.window = [[UIWindow alloc] initWithWindowScene:windowScene];
self.window.frame = windowScene.coordinateSpace.bounds;
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController: [[VCRoot alloc] init] ];
[self.window makeKeyAndVisible];
}
VCRoot.m
@implementation VCRoot
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor yellowColor];
//设置导航栏风格颜色
//UIBarStyleBlack:黑色风格,(半)透明风格
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
//将风格设置为不透明
//self.navigationController.navigationBar.translucent = NO;
//设置导航栏的颜色
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
//设置导航元素项目按钮的风格颜色
self.navigationController.navigationBar.tintColor = [UIColor systemMintColor];
self.title = @"根视图";
//🫥隐藏导航栏
//默认为NO
self.navigationController.navigationBar.hidden = NO;
self.navigationController.navigationBarHidden = NO;
UIBarButtonItem* btn = [[UIBarButtonItem alloc] initWithTitle: @"右侧按钮" style: UIBarButtonItemStylePlain target: nil action: nil];
self.navigationItem.rightBarButtonItem = btn;
//实现工具栏对象
//默认工具栏时隐藏
self.navigationController.toolbarHidden = NO;
//self.navigationController.toolbar.translucent = NO;
//创建三个工具栏按钮
UIBarButtonItem* btn01 = [[UIBarButtonItem alloc] initWithTitle: @"left" style: UIBarButtonItemStylePlain target: nil action: nil];
UIBarButtonItem* btn02 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCamera target: self action: @selector(pressNext)];
UIButton* btnImage = [UIButton buttonWithType: UIButtonTypeCustom];
[btnImage setImage: [UIImage imageNamed: @"hh"] forState: UIControlStateNormal];
btnImage.frame = CGRectMake(0, 0, 60, 60);
UIBarButtonItem* btn03 = [[UIBarButtonItem alloc] initWithCustomView: btnImage];
//固定宽度占位按钮
UIBarButtonItem* btnF01 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
btnF01.width = 80;
//创建自动计算宽度按钮
UIBarButtonItem* btnF02 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
//按钮数组的创建
NSArray* arrayBtns = [NSArray arrayWithObjects: btn01, btnF02, btn02, btn03, nil];
self.toolbarItems = arrayBtns;
}
- (void)pressNext
{
VCSecond* vc = [[VCSecond alloc] init];
[self.navigationController pushViewController: vc animated: YES];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
VSecond.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor orangeColor];
}
UIScrollView
滚动视图,可以对视图内容进行滚屏查看功能。
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//定义并创建一个滚动视图
UIScrollView* sv = [[UIScrollView alloc] init];
//设置滚动视图的位置,使用矩形来定位视图位置
sv.frame = CGRectMake(0, 0, 320, 576);
//是否按照整页来滚动视图
sv.pagingEnabled = YES;
//是否可以开启滚动效果
sv.scrollEnabled = YES;
//设置画布的大小,画布显示在滚动视图内部,一般大于frame的大小
sv.contentSize = CGSizeMake(320 * 5, 576);
//是否可以边缘弹动效果
sv.bounces = YES;
//开启横向弹动效果
sv.alwaysBounceHorizontal = YES;
//开启纵向弹动效果
sv.alwaysBounceVertical = NO;
//显示横向滚动条
sv.showsHorizontalScrollIndicator = YES;
//显示纵向滚动条
//若画布大小小于frame大小,则滚动条也不会出现
sv.showsVerticalScrollIndicator = NO;
//设置背景颜色
sv.backgroundColor = [UIColor systemMintColor];
//使用循环创建5张图片视图
for (int i = 0; i < 5; ++i) {
NSString* strName = [NSString stringWithFormat: @"%d.jpg", i + 1];
UIImage* image = [UIImage imageNamed: strName];
UIImageView* iView = [[UIImageView alloc] initWithImage: image];
iView.frame = CGRectMake(320 * i, 0, 320, 576);
[sv addSubview: iView];
}
[self.view addSubview: sv];
}
@end
UITableView
@interface ViewController : UIViewController
<
//实现数据视图的普通协议
//数据视图的普通事件处理
UITableViewDelegate,
//实现数据视图的数据代理
//处理数据视图的数据代理
UITableViewDataSource
>
//定义一个数据视图对象
//数据视图对象用来显示大量相同格式的信息的视图
//例如:电话通讯录,微信好友列表,朋友圈信息
@property(nonatomic, strong) UITableView* tableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建数据视图
//P1:数据视图的位置
//P2:数据视图的风格
//UITableViewStylePlain:普通风格
//UITableViewStyleGrouped:分组风格
self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStyleGrouped];
//设置数据视图的代理对象
self.tableView.delegate = self;
//设置数据视图的数据源代理对象
self.tableView.dataSource = self;
[self.view addSubview: self.tableView];
}
//获取每组元素的个数(行数)
//必须要实现的协议函数
//程序在显示数据视图时会调用此函数
//返回值:表示每组元素的个数
//P1:数据视图本身
//P2:哪一组需要的行数
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return 5;
}
//设置数据视图的组数
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
//创建单元格对象函数
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
NSString* cellStr = @"cell";
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier: cellStr];
if (cell == nil) {
//创建一个单元格对象
//参数一:单元格的样式
//参数二:单元格的复用标记
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: cellStr];
}
NSString* str = [NSString stringWithFormat: @"第%ld组,第%ld行", indexPath.section, indexPath.row];
//将单元格的主文字内容赋值
cell.textLabel.text = str;
return cell;
}
UITableViewCell单元格
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStylePlain];
//自动调整子视图的大小
self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//设置代理
self.tableView.delegate = self;
self.tableView.dataSource = self;
//数据视图的头部视图的设定
self.tableView.tableHeaderView = nil;
//数据视图的尾部视图的设定
self.tableView.tableFooterView = nil;
[self.view addSubview: self.tableView];
//初始化数据源数组
self.arrayData = [[NSMutableArray alloc] init];
for (int i = 1; i < 20; ++i) {
NSString* str = [NSString stringWithFormat: @"A %d", i];
[self.arrayData addObject: str];
}
//当数据的数据源发生变化时,
//更新数据视图,重新加载数据
[self.tableView reloadData];
[self createBtn];
}
- (void)createBtn
{
self.view.backgroundColor = [UIColor blackColor];
self.isEdit = NO;
//创建功能按钮
self.btnEdit = [[UIBarButtonItem alloc] initWithTitle: @"edit" style: UIBarButtonItemStylePlain target: self action: @selector(pressEdit)];
self.btnFinish = [[UIBarButtonItem alloc] initWithTitle: @"finish" style: UIBarButtonItemStylePlain target: self action: @selector(pressFinish)];
//self.btnDelete = [[UIBarButtonItem alloc] initWithTitle: @"delete" style: UIBarButtonItemStylePlain target: self action: @selector(pressDelete)];
self.navigationItem.rightBarButtonItem = self.btnEdit;
}
//可以显示编辑状态,当手指在单元格上移动时
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//删除数据源对应的数据
[self.arrayData removeObjectAtIndex: indexPath.row];
//数据源更新
[self.tableView reloadData];
NSLog(@"delete!");
}
//选中单元格调用此协议函数
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"选中单元格!%ld, %ld", indexPath.section, indexPath.row);
}
//取消选中时调用的协议函数
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"取消选中单元格!%ld, %ld", indexPath.section, indexPath.row);
}
//单元格行显示效果协议
- (UITableViewCellEditingStyle)tableView: (UITableView *)tableView editingStyleForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
//UITableViewCellEditingStyleDelete
//UITableViewCellEditingStyleInsert
//UITableViewCellEditingStyleNone
//多选状态
//UITableViewCellEditingStyleDelete | UITableViewCellEdtingStyleInsert
//默认为删除
return UITableViewCellEditingStyleDelete;
}
- (void)pressEdit
{
self.isEdit = YES;
self.navigationItem.rightBarButtonItem = self.btnFinish;
[self.tableView setEditing: YES];
self.navigationItem.leftBarButtonItem = self.btnDelete;
}
- (void)pressFinish
{
self.isEdit = NO;
self.navigationItem.rightBarButtonItem = self.btnEdit;
[self.tableView setEditing: NO];
self.navigationItem.leftBarButtonItem = nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.arrayData.count;
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
// return 1;
//}
//cell.label???
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
NSString* strID = @"ID";
//尝试获取可以复用的单元格
//如果得不到,返回为nil
UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier: strID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: strID];
}
//单元格文字赋值
cell.textLabel.text = [self.arrayData objectAtIndex: indexPath.row];
//设置子文字标题
cell.detailTextLabel.text = @"子标题";
NSString* str = [NSString stringWithFormat: @"%ld.png", indexPath.row % 8 + 1];
UIImage* image = [UIImage imageNamed: str];
//设置默认的图标信息
cell.imageView.image = image;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
@end
结束语
到这里终于是完成了实验室布置的UI学习任务,在UIKit中还有许多待学习的控件以及高级的布局、协议。由于本篇文章中一些控件初始化方式已是陈年老旧,本人将在以后的学习中将不断更新UI控件的使用并灵活使用苹果官网的文档进行查阅Apple官网UIKitFramework文档,摒弃某些已经包浆的UI使用方案。