OC—UI學習
UILabel
- UILabel是UIKit框架中的一個類
- Label主要參數
- text:文本
- frame:位置框架
- backgroundcolor:背景顏色
- textAlignment:設置文本在Label中的位置
- textColor:文本顏色
- shadowColor:陰影顏色
- shadowOffset:陰影偏移量
- numberOflines: 文本行數
- (void) createUI {//UILable是顯示在屏幕上的,并且可以顯示文字的一種UI視圖UILabel* label = [[UILabel alloc] init];//顯示文字賦值,字符串對象label.text = @"請選擇登錄界面";//設定lable的顯示位置label.frame = CGRectMake(130, 200, 160, 40);//設置UI背景色/clearColor表示透明色label.backgroundColor = [UIColor yellowColor];//將lable顯示到屏幕上[self.view addSubview:label];//調整lable文字大小,使用系統默認字體,大小為20label.font = [UIFont systemFontOfSize:22];label.textColor = [UIColor blackColor];//lable的高級屬性//設定陰影的顏色label.shadowColor = [UIColor grayColor];//設定陰影的偏移量label.shadowOffset = CGSizeMake(3, 3);//設置text文字的對齊模式,默認為靠左側對齊,center為居中對齊。right右對齊label.textAlignment = NSTextAlignmentCenter;//如果文本過長,會出現省略號,一下實現自動換行,其他的大于0的情況,文字會盡量按照設定行數顯示,如果為0,那么會對文字自動計算所需要的行數label.numberOfLines = 0;}
- CGRectMake參數:
x
:矩形左上角的 X 坐標(水平位置)。y
:矩形左上角的 Y 坐標(垂直位置)。width
:矩形的 寬度。height
:矩形的 高度。
UIButton
UIButton是UIKit框架中的一個類,繼承了UIControl的交互特性(如觸摸事件處理),用于創建可點擊的按鈕,通常用于響應用戶的觸摸事件,然后執行響應的操作或觸發特定的動作。
- 創建一個普通按鈕
//創建普通的UIButton按鈕函數
- (void)creatUIRectButton {//創建圓角類型按鈕//通過類方法來創建(button的內存是自己管理的)UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];//設置位置button.frame = CGRectMake(150, 100, 100, 40);//顯示文字//@paramemter//p1: 字符串類型,表示顯示到按鈕上的文字//p2: 設置文字顯示的狀態類型;UIControlStateNormal:正常狀態//為不同狀態設置不同文本[button setTitle:@"按鈕01" forState:UIControlStateNormal];//p1:顯示的文字//p2:顯示文字的狀態;UIControlStateHighlighted:按下狀態[button setTitle:@"按鈕按下" forState:UIControlStateHighlighted];//背景顏色button.backgroundColor = [UIColor yellowColor];//文字顏色//p1:顏色//p2:狀態[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];[button setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];//設置按鈕的風格顏色//[button setTintColor:[UIColor whiteColor]];//設置字體大小button.titleLabel.font = [UIFont systemFontOfSize:18.0];//添加到視圖中并顯示[self.view addSubview:button];
}
button通過一個正常狀態與高亮狀態,給予用戶不同的反饋
- 創建圖片按鈕
- (void)creatImageButton {//創建一個自定義類型buttonUIButton* buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];buttonImage.frame = CGRectMake(150, 200, 100, 100);//從應用束資源束中加載圖片文件并創建UIImage對象UIImage* icon01 = [UIImage imageNamed:@"button01.jpg"];UIImage* icon02 = [UIImage imageNamed:@"button02.jpg"];//p1:顯示圖片對象//p1:按鈕狀態[buttonImage setImage:icon01 forState:UIControlStateNormal];[buttonImage setImage:icon02 forState:UIControlStateHighlighted];[self.view addSubview:buttonImage];
}
注意要將圖片提前導入到項目之中,注意圖片格式
- UIButton的事件觸發
- (void)creatButton {UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];button.backgroundColor = [UIColor yellowColor];button.frame = CGRectMake(150, 100, 100, 40);[button setTitle:@"按鈕" forState:UIControlStateNormal];button.titleLabel.font = [UIFont systemFontOfSize:18];/*為按鈕添加響應時間邏輯1. target常見取值:self:當前視圖控制器或視圖nil:使用響應鏈尋找處理方法其他對象會對target產生弱引用,不會阻止target被釋放,但若target釋放后,按鈕仍然可能觸發事件(需要手動移除target)2. action:事件觸發時調用的方法,必須是target對象中實現的方法3. controlEvents:出發事件的條件*/[button addTarget:self action:@selector(pressButton:) forControlEvents:UIControlEventTouchUpInside];[button addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];[self.view addSubview:button];/*如果事件函數帶參數,那么不同按鈕調用時會有區別button.tag = 101;*/button.tag = 101;UIButton* button02 = [UIButton buttonWithType:UIButtonTypeRoundedRect];button02.tag = 102;button02.frame = CGRectMake(150, 400, 100, 40);[button02 setTitle:@"修改密碼" forState:UIControlStateNormal];[button02 setTitle:@"請修改密碼" forState:UIControlStateHighlighted];button02.titleLabel.textAlignment = NSTextAlignmentCenter;[button02 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];[button02 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];button02.backgroundColor = [UIColor yellowColor];button02.titleLabel.font = [UIFont systemFontOfSize:18.0];[button02 addTarget:self action:@selector(modifyPassword) forControlEvents:UIControlEventTouchUpInside];[button02 addTarget:self action:@selector(pressButton:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:button02];
}/*
- (void)pressButton {NSLog(@"按鈕被按下");
}
*///參數調用此函數按鈕對象本身
- (void)pressButton:(UIButton* )button {if (button.tag == 101) {NSLog(@"button01 is pressed");}if (button.tag == 102) {NSLog(@"button02 is pressed");}
}//觸碰時調用事件函數
- (void)touchDown {NSLog(@"按鈕被觸碰");
}//修改密碼觸碰后調用函數
- (void)modifyPassword {NSLog(@"請輸入新密碼");
}1. 按壓并松開最上面按鈕出現如下輸出
> 按鈕被觸碰
> button01 is pressed
2. 觸碰修改密碼密碼按鈕會出現> 請輸入新密碼
> button02 is pressed
> 根據按鈕不同的狀態(UIControlEvents)顯示不同的樣式
這里通過設置button的tag值來決定點擊事件中執行的操作
一般從0開始,便于操作
UIView基礎
UIview是ios得1視圖對象,是顯示在我們屏幕上的所有的對象的基類
所有顯示在屏幕上的對象都一定繼承與UIView,也就是說所有屏幕上可以看到的對象都是UIView的子類
UIView是一個矩形對象,有背景顏色,可以顯示,有層級關系
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.UIView* view = [[UIView alloc] init];view.frame = CGRectMake(160, 150, 100, 200);view.backgroundColor = [UIColor orangeColor];//將新建的視圖添加到父親的視圖上//過程:1.將新建的視圖添加到屏幕上;2.將視圖作為父親視圖的子視圖管理起來[self.view addSubview:view];//隱藏視圖//YES為隱藏;默認為NO顯示view.hidden = YES;//設置視圖的透明度// = 1:不透明 ; = 0:透明 ;= 0.5:半透明view.alpha = 0.5;self.view.backgroundColor = [UIColor blueColor];//設置是否顯示不透明view.opaque = NO;//將自己從父親視圖刪除//1.從父親的管理視圖中刪除//2.不會顯示在屏幕上[view removeFromSuperview];
}@end
UIView層級關系
在多個視圖同時被添加到父視圖上時,回你出現一個先添加與后添加的關系,后添加的視圖會覆蓋先添加的視圖。
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.//創建三個視圖對象UIView* view01 = [[UIView alloc] init];view01.frame = CGRectMake(100, 100, 150, 150);view01.backgroundColor = [UIColor blueColor];UIView* view02 = [[UIView alloc] init];view02.frame = CGRectMake(125, 125, 150, 150);view02.backgroundColor = [UIColor orangeColor];UIView* view03 = [[UIView alloc] init];view03.frame = CGRectMake(150, 150, 150, 150);view03.backgroundColor = [UIColor greenColor];//顯示到屏幕上,受父親視圖管理//哪一個視圖被限添加到父親視圖中,就先繪制哪一個視圖[self.view addSubview:view01];[self.view addSubview:view02];[self.view addSubview:view03];//將某一個子視圖調整到最前面[self.view bringSubviewToFront:view01];//參數:UIview對象//將某一個子視圖調整到最后面顯示[self.view sendSubviewToBack:view01];//subview:是管理所有self.view的子視圖的數組UIView* viewFront = self.view.subviews[2];[view01 removeFromSuperview];UIView* viewBack = self.view.subviews[0];if (view01 == viewBack) {NSLog(@"相等");}
}@end
注釋:就是類似效果
可以通過bringSubviewToFront:與sendSubviewToBack:方法調節視圖位置
同時也可以調用對象的removeFromSuperview方法刪除自己。
UIWindow
在現在這個版本中已經不需要創建UIWindow了,程序自己會創建,我們只用創建一個根視圖控制器來決定我們要推出那一個視圖控制器展示在用戶眼前。
- UIWindow是iOS中的一個界面對象,用于表示和管理應用程序的窗口,他通常包含應用程序的視圖層次結構的背景,并且是所有視圖控制器和視圖的容器。在應用程序中,UIWindow對象在屏幕上扮演一個至關重要的角色,他負責協調視圖對象的展示與事件的響應
是iOS應用程序中最底層的界面對象,是應用程序可視化的載體,所有視圖與視圖控制器都必須加載到UIWindow中,才能最終顯示在屏幕上
協調事件響應,當用戶觸摸屏幕時,系統會自動生成一個UIEvent(觸摸事件),并首先傳遞給UIWindow
以下現實場景:
1.消息推送彈窗:消息的懸浮通知
2.多任務多窗口:多窗口獨立
3.游戲中的彈窗菜單:游戲應用中常需要暫停游戲并彈出設置菜單
4.全屏廣告:應用程序中的全屏廣告通常會在新的UIWindow中修顯示
-
視圖控制器:
簡稱VC是MVC模式的核心組件,負責管理視圖(view)與數據(Model)之間的交互邏輯(導演)
主要功能:
1.創建和管理視圖
VC負責創建或加載視圖,并定義視圖的布局
2.視圖生命周期的管理
VC控制視圖的顯示與隱藏,并在不同階段觸發特定的方法,用于執行界面更新或資源釋放
3.事件響應
VC監聽用戶操作(如按鈕點擊、滑動手勢),并調用相應的處理方法
4.數據與界面的綁定
VC從Model層獲取數據,并更新提交到View中(如從網絡請求獲取用戶信息后,填充到界面的文本框),同時將用戶輸出的數據傳遞給Model層
5.頁面跳轉(導航)
VC通過協調不同界面之間的切換邏輯
6.父子控制器關系
復雜界面可通過容器視圖管理器管理子控制器
視圖:負責界面元素的展示,如按鈕、文本框、圖片等
數據:村醋界面元素需要展示的內容,如用戶信息,網絡請求結果等。
#import "SceneDelegate.h"@interface SceneDelegate ()@end@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).self.window.rootViewController = [[UIViewController alloc] init];self.window.backgroundColor = [UIColor blueColor];UIView* view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 150, 150)];view.backgroundColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.5 alpha:0];UIView* backview = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];backview.backgroundColor = [UIColor orangeColor];[backview addSubview:view];/*子視圖的坐標參照父親視圖的坐標當父親視圖移動時,所有的子視圖都會移動*/[self.window addSubview:backview];/*每一個view都有一個window屬性打印出結果發現地址都相同,說明是同一個window當我們把子視圖添加到父視圖上時,會將父視圖的window賦給子視圖的window*/NSLog(@"%@",view.window);NSLog(@"%@",backview.window);NSLog(@"%@",self.window);/*<UIWindow: 0x10590f1d0; frame = (0 0; 402 874); hidden = YES; gestureRecognizers = <NSArray: 0x600000c6dbc0>; backgroundColor = UIExtendedSRGBColorSpace 0 0 1 1; layer = <UIWindowLayer: 0x600000c69f20>><UIWindow: 0x10590f1d0; frame = (0 0; 402 874); hidden = YES; gestureRecognizers = <NSArray: 0x600000c6dbc0>; backgroundColor = UIExtendedSRGBColorSpace 0 0 1 1; layer = <UIWindowLayer: 0x600000c69f20>><UIWindow: 0x10590f1d0; frame = (0 0; 402 874); hidden = YES; gestureRecognizers = <NSArray: 0x600000c6dbc0>; backgroundColor = UIExtendedSRGBColorSpace 0 0 1 1; layer = <UIWindowLayer: 0x600000c69f20>>*/[self.window makeKeyAndVisible];}- (void)sceneDidDisconnect:(UIScene *)scene {// Called as the scene is being released by the system.// This occurs shortly after the scene enters the background, or when its session is discarded.// Release any resources associated with this scene that can be re-created the next time the scene connects.// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}- (void)sceneDidBecomeActive:(UIScene *)scene {// Called when the scene has moved from an inactive state to an active state.// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}- (void)sceneWillResignActive:(UIScene *)scene {// Called when the scene will move from an active state to an inactive state.// This may occur due to temporary interruptions (ex. an incoming phone call).
}- (void)sceneWillEnterForeground:(UIScene *)scene {// Called as the scene transitions from the background to the foreground.// Use this method to undo the changes made on entering the background.
}- (void)sceneDidEnterBackground:(UIScene *)scene {// Called as the scene transitions from the foreground to the background.// Use this method to save data, release shared resources, and store enough scene-specific state information// to restore the scene back to its current state.
}@end
UIController
我們的項目在創建時會同步創建一對UIViewController文件
調用關系為:
Appdeledate.m -> SceneDelegate.m -> ViewController.m
- 一個視圖推出另一個視圖
#import "ViewController.h"
#import "ViewC02.h"
@interface ViewController ()@end@implementation ViewController//第一次程序加載視圖時調用,只能加載一次
- (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視圖即將消失");
}//*****animated表示視圖即將消失的過程是否是用動畫,他有兩種可能的值YES or NO******/*當視圖已經顯示到屏幕后的瞬間調用次函數參數:表示是否用動畫切換顯示的當前狀態已經顯示到屏幕上了*/
- (void)viewDidAppear:(BOOL)animated {NSLog(@"viewDidAppear當前視圖已經顯示");
}/*當前視圖已經從屏幕上消失了參數:表示是否用動畫來切換的當前視圖已經從屏幕上消失*/
- (void)viewDidDisappear:(BOOL)animated {NSLog(@"veiwDidDisappear視圖已經消失");
}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {ViewC02* vc = [[ViewC02 alloc] init];/*顯示一個新的視圖控制器界面到屏幕上參數:p1:新的控制器對象p2:是否使用動畫效果p3:切換結束后功能調用,如果不需要就直接傳空*/[self presentViewController:vc animated:YES completion:nil];
}@end#import "ViewC02.h"@interface ViewC02 ()@end@implementation ViewC02- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.//設置控制器2的顏色self.view.backgroundColor = [UIColor orangeColor];}//當點擊當前控制器二的界面屏幕時
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {/*使當前的控制器消失掉參數:p1:是否有動畫效果p2:是否調用塊中函數*/[self dismissViewControllerAnimated:YES completion:nil];
}/*當我們的視圖控制器即將顯示時調用次函數視圖分為:1.顯示前(不顯示)2.正在處于顯示狀態 3.已經被隱藏參數:表示是否有動畫切換后顯示每一次視圖顯示時都要被調用*/
- (void)viewWillAppear:(BOOL)animated {NSLog(@"viewWillAppear即將顯示");
}/*視圖即將消失調用此函數參數:表示是否動畫切換后消失當前的狀態:視圖還是顯示在屏幕上的*/
- (void)viewWillDisappear:(BOOL)animated {NSLog(@"viewWillDisappear視圖即將消失");
}//*****animated表示視圖即將消失的過程是否是用動畫,他有兩種可能的值YES or NO******/*當視圖已經顯示到屏幕后的瞬間調用次函數參數:表示是否用動畫切換顯示的當前狀態已經顯示到屏幕上了*/
- (void)viewDidAppear:(BOOL)animated {NSLog(@"viewDidAppear當前視圖已經顯示");
}/*當前視圖已經從屏幕上消失了參數:表示是否用動畫來切換的當前視圖已經從屏幕上消失*/
- (void)viewDidDisappear:(BOOL)animated {NSLog(@"veiwDidDisappear視圖已經消失");
}/*
#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
為什么在 touchesBegan:
中創建 ViewC02
?
- 交互觸發:代碼的意圖是用戶觸摸屏幕時彈出一個新界面。
- 按需創建:視圖控制器是比較重量級的對象,不需要提前創建,而是在用戶需要時才實例化。
- 動態呈現:通過
presentViewController:
方法將新控制器以模態方式顯示在當前界面上方,覆蓋原內容。
NSTimer
(定時器與視圖移動)
NSTimer類方法創建一個定時器并且啟動這個定時器
p1:間隔時間,以秒為單位
p2:表示實現定時器函數的對象
p3:表示定時器函數對象
p4:定時器函數中的一個參數沒有參數可以傳nil
p5:表示定時器是否可以重復
返回值:一個新建好的定時器對象
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController
//屬性與成員變量同步
//@synthesize timerView = _timerView;- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];button.frame = CGRectMake(100, 100, 80, 40);[button setTitle:@"啟動定時器" forState:UIControlStateNormal];[button addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];button.backgroundColor = [UIColor orangeColor];[self.view addSubview:button];UIButton* buttonstop = [UIButton buttonWithType:UIButtonTypeRoundedRect];buttonstop.frame = CGRectMake(100, 200, 80, 40);buttonstop.backgroundColor = [UIColor purpleColor];[buttonstop setTitle:@"停止計時器" forState:UIControlStateNormal];[buttonstop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:buttonstop];UIView* view = [[UIView alloc]init];view.frame = CGRectMake(0, 0, 80, 80);view.backgroundColor = [UIColor yellowColor];[self.view addSubview:view];//設置view的標簽值//通過父視圖對象以及view的標簽值可以獲得相應的視圖對象view.tag = 101;}//按下開始按鈕時調用
- (void)pressStart {//避免多次創建導致停不下在if (_timerView != nil) {[_timerView invalidate];}_timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"小明say" repeats:YES];
}- (void)updateTimer:(NSTimer*) timer{NSLog(@"%@你是彭于晏",timer.userInfo);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 != nil) {[_timerView invalidate];}
}@end```**UIView 的 frame 屬性**- `frame` 是 `UIView` 的一個重要屬性,類型為 `CGRect`(矩形區域),定義了視圖在**父視圖坐標系中的位置和大小**。- ```CGRect
由兩個結構體組成:
origin
(CGPoint
類型):視圖左上角的坐標點,包含x
和y
兩個值。size
(CGSize
類型):視圖的寬度和高度,包含width
和height
兩個值。
UISwitch
定義一個開關控件
可以進行狀態的改變
所有UIKit框架庫中的控件均以UI開頭
蘋果官方的控件都定義在UIKit框架庫中
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property(nonatomic, retain)UISwitch* mySwitch;
@end
///#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view./*創建一個開關對象繼承與UIView*/_mySwitch = [[UISwitch alloc] init];/*蘋果官方的控件的位置設置位置x、y的值可以改變寬高無法改變*/_mySwitch.frame = CGRectMake(100, 100, 80, 40);/*開關狀態設置屬性*/_mySwitch.on = YES; //默認狀態[_mySwitch setOn:YES animated:YES];//_mySwitch.backgroundColor = [UIColor yellowColor];/*添加視圖顯示*/[self.view addSubview:_mySwitch];//設置開啟狀態風格顏色//[_mySwitch setOnTintColor:[UIColor redColor]];//設置開關圓按鈕的風格顏色//[_mySwitch setThumbTintColor:[UIColor greenColor]];//設置整體風格顏色//[_mySwitch setTintColor:[UIColor orangeColor]];/*響應事件UIControlEventValueChanged:狀態發生變化觸發*/[_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];}- (void)swChange :(UISwitch*) sw{//on表示當前結束后的狀態if (sw.on == YES) {NSLog(@"開關被打開");} else {NSLog(@"開關被關閉");}
}
@end
UISlider與UIProgressView
#import <UIKit/UIKit.h>@interface ViewController : UIViewController
//進度條定義
@property(nonatomic, retain)UIProgressView* progressView;
//滑動條定義
@property(nonatomic, retain)UISlider* slider;
@end#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.//進度條創建_progressView = [[UIProgressView alloc] init];//進度條位置大小設置(高度不可調)_progressView.frame = CGRectMake(50, 100, 300, 40);//設置風格顏色值_progressView.progressTintColor = [UIColor redColor];_progressView.trackTintColor = [UIColor yellowColor];//設置進度條的進度值//范圍0-1_progressView.progress = 0.3;//設置進度條風格特征_progressView.progressViewStyle = UIProgressViewStyleDefault;[self.view addSubview:_progressView];//滑動條創建_slider = [[UISlider alloc] init];_slider.frame = CGRectMake(20, 200, 350, 40);//設置滑動條最大值_slider.maximumValue = 100;//最小值(可以為負值)_slider.minimumValue = 0;//設置滑塊位置(去取決于最大最小值)float類型_slider.value = 40;//左側滑動條的背景顏色_slider.minimumTrackTintColor = [UIColor blueColor];//右側滑動條的背景顏色_slider.maximumTrackTintColor = [UIColor yellowColor];//設置滑塊的顏色_slider. thumbTintColor = [UIColor orangeColor];//對滑動條添加事件函數//UIControlEventValueChanged:變化就調用[_slider addTarget:self action:@selector(pressSlider) forControlEvents:UIControlEventValueChanged];[self.view addSubview:_slider];
}- (void) pressSlider {/*進度條與滑動條同步*///_progressView.progress = _slider.value; //范圍相同_progressView.progress = (_slider.value - _slider.minimumValue) / (_slider.maximumValue - _slider.minimumValue);NSLog(@"value = %f", _slider.value);
}
@end
步進器與分欄控制器
//
// ViewController.m
// UIearn
//
// Created by xiaoli pop on 2025/5/26.
//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//滑動條_slider = [[UISlider alloc] init];_slider.frame = CGRectMake(10, 400, 200, 20);_slider.maximumTrackTintColor = [UIColor blueColor];_slider.minimumTrackTintColor = [UIColor orangeColor];[self.view addSubview:_slider];_stepper = [[UIStepper alloc] init];//寬高不可改變_stepper.frame = CGRectMake(100, 100, 80, 40);//設置最值_stepper.minimumValue = 0;_stepper.maximumValue = 100;//設置當前值_stepper.value = 10;//步進值_stepper.stepValue = 1;//是否可以重復響應事件操作_stepper.autorepeat = YES;/*是否可以將步進結果通過事件函數響應出來就是說會不會同步響應*/_stepper.continuous = YES;//添加一個事件函數[_stepper addTarget:self action:@selector(stepChange:) forControlEvents:UIControlEventValueChanged];[self.view addSubview:_stepper];//創建分欄控件_segControl = [[UISegmentedControl alloc] init];//寬度可變,高度不可變_segControl.frame = CGRectMake(10, 300, 300, 40);/*添加一個按鈕元素參數:1.按鈕文字2.按鈕位置3.是否有插入的動畫效果*/[_segControl insertSegmentWithTitle:@"安康" atIndex:0 animated:NO];[_segControl insertSegmentWithTitle:@"西安" atIndex:1 animated:NO];[_segControl insertSegmentWithTitle:@"延安" atIndex:2 animated:NO];[_segControl insertSegmentWithTitle:@"寶雞" atIndex:3 animated:NO];//設置選擇默認按鈕索引_segControl.selectedSegmentIndex = 0;//添加響應事件[_segControl addTarget:self action:@selector(segChange) forControlEvents:UIControlEventValueChanged];[self.view addSubview: _segControl];}
- (void)stepChange:(UIStepper*)step {NSLog(@"%f", step.value);
}- (void)segChange {NSLog(@"%@", [_segControl titleForSegmentAtIndex:_segControl.selectedSegmentIndex]);
}
@end
- 獲取對應index的
[_segControl titleForSegmentAtIndex:_segControl.selectedSegmentIndex]
TextField
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];_textField = [[UITextField alloc] init];_textField.frame = CGRectMake(100, 350, 180, 40);_textField.font = [UIFont systemFontOfSize:15];_textField.textColor = [UIColor blackColor];/*UITextBorderStyleRoundedRect:圓角風格UITextBorderStyleLine:線框風格UITextBorderStyleBezel:beze線框UITextBorderStyleNone:無邊框風格*/_textField.borderStyle = UITextBorderStyleRoundedRect;/*設置虛擬鍵盤風格UIKeyboardTypeDefault:默認UIKeyboardTypeNamePhonePad:字母加數字UIKeyBoardTypeNumberPad:純數字*/_textField.keyboardType = UIKeyboardTypeDefault;/*提示文字信息當text屬性為空時,顯示此條信息淺灰色*/_textField.placeholder = @"請輸入用戶名";/*是否作為密碼輸入YES:加密輸入NO:正常輸入*/_textField.secureTextEntry = NO;_textField.delegate = self;[self.view addSubview:_textField];}
- (void)textFieldDidBeginEditing:(UITextField *)textField {NSLog(@"正在進行編輯");
}- (void)textFieldDidEndEditing:(UITextField *)textField {_textField.text = @" ";NSLog(@"編輯已經結束");
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {return YES;
}- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {if (_textField.text.length < 8) {return NO;} else {return YES;}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {//使虛擬鍵盤回收,不作為消的第一響應著[_textField resignFirstResponder];//[self.view endEditing:YES];
}
@end
警告對話框與等待提示器
#import <UIKit/UIKit.h>@interface ViewController : UIViewController
/*定義一個警告對話框視圖對象*/
@property(nonatomic, retain)UIAlertController* alertcontroller;
/*當下載。或者加載比較大的文文件時,可以顯示此控件,處于提示等待狀態*/
@property(nonatomic, retain)UIActivityIndicatorView* activityIndicator;
@end//
// ViewController.m
// UIearn
//
// Created by xiaoli pop on 2025/5/26.
//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];/*創建兩個按鈕*/for (int i = 0; i < 2; i++) {UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];button.frame = CGRectMake(150, 100 + 100 * i, 100, 40);if (!i) {[button setTitle:@"警告對話框" forState:UIControlStateNormal];} else if (i == 1) {[button setTitle:@"等待對話框" forState:UIControlStateNormal];}button.backgroundColor = [UIColor greenColor];button.tag = 101 + i;[button addTarget:self action:@selector(pressButton:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:button];}}- (void)pressButton:(UIButton*)button {// 警告對話框if (button.tag == 101) {_alertcontroller = [UIAlertController alertControllerWithTitle:@"警告" message:@"手機電量過低" preferredStyle:UIAlertControllerStyleAlert];//添加一個取消按鈕UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];//將取消按鈕添加到對話框中[_alertcontroller addAction:cancleAction];UIAlertAction* newAction = [UIAlertAction actionWithTitle:@"新的" style:UIAlertActionStyleDefault handler:nil];[_alertcontroller addAction:newAction];//添加一個確認按鈕UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {NSLog(@"點擊了確認按鈕");}];[_alertcontroller addAction:confirmAction];[self presentViewController:_alertcontroller animated:YES completion:nil];} else if (button.tag == 102) {//創建等待提示器_activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(157, 300, 100, 100)];//設置提示風格_activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge;[self.view addSubview:_activityIndicator];//啟動動畫并顯示[_activityIndicator startAnimating];}
}
@end
在iOS13后設定的等待提示器風格只有UIActivityIndicatorViewStyleLarge和UIActivityIndicatorViewStyleMedium兩種風格
UIScrollView
/*定義并創建一個滾動視圖可以對視圖內容進行滾屏查看功能
*/
UIScrollView* sv = [[UIScrollView alloc] init];
/*設置滾動視圖的位置,使用矩形來定位視圖位置*/
CGRect screenBounds = [[UIScreen mainScreen] bounds];
sv.frame = screenBounds;
/*是否按照整頁來滾動視圖*/
sv.pagingEnabled = YES;
/*是否開啟滾動效果*/
sv.scrollEnabled = YES;
/*設置畫布大小,畫布顯示在滾動視圖內部,一般大于Frame的大小*/
sv.contentSize = CGSizeMake(screenBounds.size.width * 5, screenBounds.size.height);
/*是否開啟邊緣彈動效果*/
sv.bounces = YES;
/*開啟橫向彈動效果*/
sv.alwaysBounceHorizontal = YES;
/*開啟縱向彈動效果*/
sv.alwaysBounceVertical = YES;
/*開啟橫向顯示滾動條*/
sv.showsHorizontalScrollIndicator = YES;
/*開啟縱向顯示滾動條*/
sv.showsVerticalScrollIndicator = YES;
sv.backgroundColor = [UIColor yellowColor];
for (int i = 1; i <= 5; i++) {NSString* strName = [NSString stringWithFormat:@"photo0%d.jpg",i];UIImage* image = [UIImage imageNamed:strName];UIImageView* iview = [[UIImageView alloc] initWithImage:image];iview.frame = CGRectMake(screenBounds.size.width * (i - 1), 0, screenBounds.size.width, screenBounds.size.height);[sv addSubview:iview];
}
[self.view addSubview:sv];
UIScrollView的高級功能
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController
- (void)viewDidLoad {[super viewDidLoad];_scrollView = [[UIScrollView alloc] init];CGRect screenBounds = [[UIScreen mainScreen] bounds];_scrollView.frame = CGRectMake(0, 65, screenBounds.size.width, screenBounds.size.height * 0.75);//取消彈動效果_scrollView.bounces = NO;/*是否允許通過點擊屏幕讓滾動視圖響應事件YES:滾動視圖可以接受觸碰事件NO:不接受觸碰事件*///_scrollView.userInteractionEnabled = NO;_scrollView.contentSize = CGSizeMake(screenBounds.size.width , screenBounds.size.height * 5 * 0.75);for (int i = 1; i <= 5; i++) {NSString* strName = [NSString stringWithFormat:@"photo0%d.jpg",i];UIImage* image = [UIImage imageNamed:strName];UIImageView* iview = [[UIImageView alloc] initWithImage:image];//設置圖像在滾動視圖畫布中的位置iview.frame = CGRectMake(0, screenBounds.size.height * (i - 1) * 0.75, screenBounds.size.width, screenBounds.size.height);[_scrollView addSubview:iview];}[self.view addSubview:_scrollView];//滾動視圖畫布的移動位置,(偏移位置)//決定畫布顯示的最終圖像結果_scrollView.contentOffset = CGPointMake(0, 0);_scrollView.pagingEnabled = NO;_scrollView.delegate = self;}//當滾動視圖移動時,只要offet坐標發生變化,都會調用此函數
//可以使用次函數監控滾動視圖的位置
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {NSLog(@"y = %f", scrollView.contentOffset.y);
}//當滾動視圖結束拖動時調用次函數
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {NSLog(@"Did End Drag");
}//滾動視圖即將開始被拖動時
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {NSLog(@"Will begin Drag");
}//視圖即將結束拖動時調用
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {NSLog(@"Will end Drag");
}- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {NSLog(@"Will Begin Decelereting");
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {NSLog(@"視圖停止移動");
}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {CGRect screenBounds = [[UIScreen mainScreen] bounds];//_scrollView.contentOffset = CGPointMake(0, 0);[_scrollView scrollRectToVisible:CGRectMake(0, 0, screenBounds.size.width, screenBounds.size.height) animated:YES];
}@end