說明:這個專題,是介紹了一些常用的普通空間的屬性和使用,包括:UITextField、UITextView、UILabel、UIButton、UISlider、UIStepper、UIImageView、UISwitch、UISegmentedControl、UIToolBar。
0.UIView常用的屬性和操作
這是ios-UI繼承關系圖
任何控件都繼承自UIView,因此UIView里面包裝了一些控件的共有屬性和通過的方法。
0_1.UIView常見的屬性
1.frameframe是一個CGRect類型的成員變量,用來設置控件要顯示的位置frame.origin和尺寸frame.size,其中位置是在父控件中的位置,以父控件的左上角為原點。
如果要修改一個控件的frame不可以直接修改內部結構體的值,如frame.origin.x = 100;是不可以的,應該將其取出,修改之后,再重新賦值,看下面的例子:
// 1.先取出frame CGRect tempFrame = self.btn.frame; // 2.修改y值 tempFrame.origin.y -= 50; // 3.重新賦值按鈕的frame self.btn.frame = tempFrame;2.bounds
bounds也是一個CGRect類型的成員變量,但是bounds.origin.x和bounds.origin.y始終為0;bounds.size.width和bounds.size.height的值分別等於frame.size.width和frame.size.height。
center是一個CGPoint類型的成員變量,表示控件的中點在父控件中的位置,以父控件的左上角為原點。
tag是NSInteger類型的成員變量,用於標識一個空間,以便操作這個控件,例如:當兩個button都設置了同一個方法為點擊的處理事件,可以設置兩個按鈕的tag為1和2,然后在方法中分別處理:
- (IBAction)btnClick:(id)sender
{
switch ([sender tag])
{
case 1:
NSLog(@"點擊了按鈕1--");
break;
case 2:
NSLog(@"點擊了按鈕2--");
break;
default:
break;
}
}
下面是一個讓按鈕可以向上、向下、向左、向右移動的例子,並為移動過程添加了動畫
- (void) btnClickWithBlock:(void (^)())block{
// 0.動畫(頭部--開始動畫)
[UIView beginAnimations:nil context:nil];
// 設置動畫的執行時間
[UIView setAnimationDuration:1.0];
block();
// 4.動畫(尾部--提交動畫--執行動畫)
[UIView commitAnimations];
}
#pragma mark 控制按鈕走動(上下左右)
- (IBAction)run:(id)sender {
[self btnClickWithBlock:^{
// 1.先取出frame
CGRect tempFrame = self.btn.frame;
// 2.修改x,y值
switch ([sender tag]) {
case 1:
tempFrame.origin.y -= kDelta;
break;
case 2:
tempFrame.origin.x += kDelta;
break;
case 3:
tempFrame.origin.y += kDelta;
break;
case 4:
tempFrame.origin.x -= kDelta;
break;
default:
break;
}
// 3.重新賦值按鈕的frame
self.btn.frame = tempFrame;
}
如果使用center屬性來移動位置,代碼又簡化了一點,因為center的值是可以直接修改的:(下面僅僅修改移動部分的代碼)
#pragma mark 控制按鈕走動(上下左右)
- (IBAction)run:(id)sender {
[self btnClickWithBlock:^{
// 使用center的方案
CGPoint tempCenter = self.btn.center;
switch ([sender tag]) {
case 1:
tempCenter.y -= kDelta;
break;
case 2:
tempCenter.x += kDelta;
break;
case 3:
tempCenter.y += kDelta;
break;
case 4:
tempCenter.x -= kDelta;
break;
default:
break;
}
self.btn.center = tempCenter;
}];
}
5.superview
superview是UIView *類型的成員變量,它的值為當前控件的父控件
subviews是NSArray *類型的成員變量,它的值為當前控件的子控件組成的數組,在數組中的順序與加入到當前控件的順序一致。
transform是一個CGAffineTransform類型的成員變量,它是一個結構體類型,表示形變的參數(設置這個參數后,控件會按照這個參數進行形變,參數指定了變形后的終態),形變的類型有多種,包括旋轉、放縮等,默認的值為CGAffineTransformIdentity。下面是一些該屬性的使用示例,為了使用動畫,用到了前面的btnClickWithBlock:方法
- (IBAction)leftRotate:(id)sender {
// 弧度制 角度 以順時針為正向,負數為左旋轉
[self btnClickWithBlock:^{
self.btn.transform = CGAffineTransformRotate(self.btn.transform, -M_PI_4);// 向左旋轉45度 這個函數的第一個參數為形變初態,第二個參數指定了終態 注意和下面的區別
// self.btn.transform = CGAffineTransformMakeRotation(-M_PI_4);// 控件內部會記錄形變初態,若執行一次這句代碼會旋轉一次,若再次執行不會再旋轉,因為旋轉一次后已經和指定的終態相同。而上面的代碼,會將上次旋轉后的狀態設置為本次旋轉的初態,因而每次執行都會旋轉
}];
}
#pragma mark - 放大
- (IBAction)big:(id)sender {
[self btnClickWithBlock:^{
self.btn.transform = CGAffineTransformScale(self.btn.transform, 1.2, 1.2);// 寬和高放大為1.2倍
}];
}
#pragma mark - 重置為默認的狀態
- (IBAction)reset:(id)sender {
[self btnClickWithBlock:^{
self.btn.transform = CGAffineTransformIdentity;
}];
}
0_2.UIView狀態
UIView有不同的狀態:以按鈕UIButton為例就有這樣幾種狀態:默認Default,高亮Highlighted,選中Selected,不可用Disabled。不同的狀態下有相同的屬性,例如上面提到的幾種屬性,在編碼時千萬注意不可將不同的狀態下的屬性混用了。UIView通常包含上面四中狀態,很多人對高亮狀態和選中狀態不易區分:高亮Highlighted是正在選擇時(觸摸到時,或者長按時)的狀態,而選中Selected則是點選后的狀態,官方有下面的解釋:
UIControlStateHighlighted Highlighted state of a control. A control enters this state when a touch enters and exits during tracking and when there is a touch up event. You can retrieve and set this value through the highlighted property. Available in iOS 2.0 and later. Declared in UIControl.h. UIControlStateSelected Selected state of a control. For many controls, this state has no effect on behavior or appearance. But other subclasses (for example, the UISegmentedControl class) may have different appearance depending on their selected state. You can retrieve and set this value through the selected property. Available in iOS 2.0 and later. Declared in UIControl.h.
0_3.UIView常用的方法
這部分將使用代碼創建一些控件的方式展示一些UIView的常用方法。首先要明確一點代碼應該添加到什么地方,通常控制器負責界面的初始化,控制器首先會加載storyboard中的界面然后執行viewDidLoad方法,因此可以在viewDidLoad方法中添加一些其他的控件
@implementation ViewController
#pragma mark 控制器的view加載完畢的時候會調用一次
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 創建一個按鈕
// 1.1創建
UIButton *btn = [[UIButton alloc] init];
// 1.2設置按鈕的尺寸和位置
btn.frame = CGRectMake(0, 0, 100, 100);
// 1.3設置按鈕的普通狀態下的屬性
// 1.3.1設置背景圖片
UIImage *normal = [UIImage imageNamed:@"btn_01.png"];
[btn setBackgroundImage:normal forState:UIControlStateNormal];
// 1.3.2 設置文字
[btn setTitle:@"normal" forState:UIControlStateNormal];
// 1.3.3 設置文字顏色
[btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
// 1.4設置按鈕的高亮狀態下的屬性
// 1.4.1設置背景圖片
UIImage *high = [UIImage imageNamed:@"btn_02.png"];
[btn setBackgroundImage:high forState:UIControlStateHighlighted];
// 1.4.2 設置文字
[btn setTitle:@"highlighted" forState:UIControlStateHighlighted];
// 1.4.3 設置文字顏色
[btn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
// 1.5 監聽按鈕點擊
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
// 2.添加按鈕到控制器的view中
[self.view addSubview:btn];
// 3.添加文本輸入框
UITextField *txtField = [[UITextField alloc] init];
txtField.backgroundColor = [UIColor redColor];
txtField.frame = CGRectMake(0, 0, 100, 100);
txtField.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
// txtField.center = self.view.center; // 這種方法不行**************為什么
// 設置字體
txtField.font = [UIFont systemFontOfSize:30];
[self.view addSubview:txtField];
}
#pragma mark 監聽按鈕點擊
- (void)btnClick:(id)sender
{
NSLog(@"按鈕%p被點擊", sender);
}
@end
在寫上面的例子的時候,發現txtField.center = self.view.center;這句代碼並不能使txtField居中,進行如下的測試
NSLog(@"%f,%f", self.view.frame.size.width, self.view.frame.size.height); NSLog(@"%f,%f", self.view.center.x, self.view.center.y);其結果為:
2015-02-13 17:44:13.135 02-代碼創建按鈕[1674:907] 320.000000,460.000000 2015-02-13 17:44:13.136 02-代碼創建按鈕[1674:907] 160.000000,250.000000
center是代表當前控件的中點在父控件中的位置,仔細思考后推測應該是這個原因:手機屏幕最上方電池電量一欄占用了20高度,而self.view的父控件是整個手機屏幕,於是會有上面的輸出結果,於是我繼續添加一個scrollView到storyboard,調整尺寸為320*460並且剛好占滿view,於是再進行測試:
NSLog(@"%f,%f", self.view.frame.size.width, self.view.frame.size.height); NSLog(@"%f,%f", self.view.center.x, self.view.center.y); NSLog(@"%f,%f", self.scroll.center.x, self.scroll.center.y);
這次的結果為:
2015-02-13 18:03:20.151 02-代碼創建按鈕[1777:907] 320.000000,460.000000 2015-02-13 18:03:20.152 02-代碼創建按鈕[1777:907] 160.000000,250.000000 2015-02-13 18:03:20.152 02-代碼創建按鈕[1777:907] 160.000000,230.000000
但是當我要用
NSLog(@"%f,%f", self.view.superview.frame.size.width, self.view.superview.frame.size.height);
輸出self.view父控件的寬高時,其結果竟然是0和0,雖然無法通過代碼得出self.view父控件的寬高,但是已經有了如下的結論:
1.self.view父控件的寬高為:320*480, 其center屬性為x=160,y=250,占去的高度20為電池電量欄高度
2.一定注意center屬性是當前控件中心在父控件中的位置
回過神來,繼續說說UIView的常用方法,在剛才的示例程序中,有幾個方法要着重說明一下:
1.在設置控件的背景顏色、文字、和文字顏色的時候需要傳遞控件狀態的參數,表示該狀態下的背景顏色、文字和文字顏色。
2.要為控件添加事件處理的方法
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
action參數是事件的處理方法名;target參數是已經實現了action方法的類的實例;參數forControlEvents為事件名稱。
1.文本框UITextField和文本視圖UITextView
UI控件中最基本的兩個用於輸入的控件UITextFiled和UITextView,其中UITextField是單行的UITextView是多行的。1_1.文本框UITextField
在iOS應用中,文本框UITextField是一種常見的信息輸入控件,類似於Web表單中的表單字段。當在文本框中輸入數據時,可以使用各種iOS鍵盤將其輸入限制為數字或者文本。和按鈕一樣,文本框也能相應事件,但是通常將其實現為被動(passive)界面元素,這意味着視圖控制器可隨時通過text屬性讀取其內容。
UITextField控件的常用屬性(幾乎包含了iOS控件的所有的通用屬性)如下:
1.borderStyle屬性:設置輸入框的邊框線樣式。主要有以下4種取值:
typedef NS_ENUM(NSInteger, UITextBorderStyle) {
UITextBorderStyleNone, // 無樣式
UITextBorderStyleLine, // 直線
UITextBorderStyleBezel, // 上邊框和左邊框加重
UITextBorderStyleRoundedRect // 圓角
};
分別使用每個UITextBorderStyle樣式創建4個控件:
- (void)viewDidLoad
{
[super viewDidLoad];
UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(20, 30, 200, 40)];
textField1.borderStyle = UITextBorderStyleNone;
UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(20, 80, 200, 40)];
textField2.borderStyle = UITextBorderStyleLine;
UITextField *textField3 = [[UITextField alloc] initWithFrame:CGRectMake(20, 130, 200, 40)];
textField3.borderStyle = UITextBorderStyleBezel;
UITextField *textField4 = [[UITextField alloc] initWithFrame:CGRectMake(20, 180, 200, 40)];
textField4.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField1];
[self.view addSubview:textField2];
[self.view addSubview:textField3];
[self.view addSubview:textField4];
}
演示效果如下:

backgroundColor屬性:設置輸入框的背景顏色。
3.
font屬性:設置輸入字體。
4.
textColor屬性:設置字體顏色。
5.
placeholder屬性:設置輸入框內默認的文字。alpha為0.7
6.
textAlignment屬性:設置輸入框內內容的對齊方式。取值為以下幾種:
typedef NS_ENUM(NSInteger, NSTextAlignment) {
NSTextAlignmentLeft = 0, // Visually left aligned
#if TARGET_OS_IPHONE
NSTextAlignmentCenter = 1, // Visually centered
NSTextAlignmentRight = 2, // Visually right aligned
#else /* !TARGET_OS_IPHONE */
NSTextAlignmentRight = 1, // Visually right aligned
NSTextAlignmentCenter = 2, // Visually centered
#endif
NSTextAlignmentJustified = 3, // Fully-justified. The last line in a paragraph is natural-aligned.
NSTextAlignmentNatural = 4, // Indicates the default alignment for script
} NS_ENUM_AVAILABLE_IOS(6_0);
可以看到這是一個iOS和mac開發的通用屬性,枚舉字面量相同但是值不同。
7.contentVerticalAlignment屬性:設置內容的垂直對齊方式。UITextField繼承自UIControl,此類中有一個屬性contentVerticalAlignment,其取值為以下三種:
typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {
UIControlContentHorizontalAlignmentCenter = 0,
UIControlContentHorizontalAlignmentLeft = 1,
UIControlContentHorizontalAlignmentRight = 2,
UIControlContentHorizontalAlignmentFill = 3,
};
8.
background屬性:設置一個背景圖片。注意:當UITextBorderStyle的值為UITextBorderStyleRoundedRect時,無法設置。
9.
disabledBackground屬性:設置一個在不可用狀態下(textField.enabled = NO;)的背景圖片。注意:如果background的值沒有設置,則會讓這個值失效。
10.
clearButtonMode屬性:設置一個清空按鈕,通過設置clearButtonMode可以指定是否以及何時顯示清除按鈕。取值主要有如下幾種類型:
- ∆
UITextFieldViewModeAlways:不為空,一直都顯示清空按鈕; - ∆
UITextFieldViewModeNever:不顯示清空按鈕; - ∆
UITextFieldViewModeWhileEditing:不為空,且在編輯狀態時(即獲得焦點)顯示清空按鈕; - ∆
UITextFieldViewModeUnlessEditing:不為空,不在編輯狀態時,顯示清空按鈕;
text屬性:設置輸入框一開始就有的文字。
12.
secureTextEntry屬性:每輸入一個字符就變成點,用於密碼輸入。
13.
autocorrectionType屬性:設置是否糾錯。取值有以下幾種
typedef NS_ENUM(NSInteger, UITextAutocorrectionType) {
UITextAutocorrectionTypeDefault,
UITextAutocorrectionTypeNo,
UITextAutocorrectionTypeYes,
};
14.
clearsOnBeginEditing屬性:設置再次編輯是否清空。
15.
adjustsFontSizeToFitWidth屬性:設置為YES時文本會自動縮小以適應文本窗口大小.默認是保持原來大小,而讓長文本滾動。
16.
minimumFontSize屬性:設置自動縮小顯示的最小字體大小。
17.
keyboardType屬性:設置鍵盤的樣式。其取值有以下幾種:
typedef NS_ENUM(NSInteger, UIKeyboardType) {
UIKeyboardTypeDefault, // Default type for the current input method.
UIKeyboardTypeASCIICapable, // Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain active
UIKeyboardTypeNumbersAndPunctuation, // Numbers and assorted punctuation.
UIKeyboardTypeURL, // A type optimized for URL entry (shows . / .com prominently).
UIKeyboardTypeNumberPad, // A number pad (0-9). Suitable for PIN entry.
UIKeyboardTypePhonePad, // A phone pad (1-9, *, 0, #, with letters under the numbers).
UIKeyboardTypeNamePhonePad, // A type optimized for entering a person's name or phone number.
UIKeyboardTypeEmailAddress, // A type optimized for multiple email address entry (shows space @ . prominently).
#if __IPHONE_4_1 <= __IPHONE_OS_VERSION_MAX_ALLOWED
UIKeyboardTypeDecimalPad, // A number pad with a decimal point.
#endif
#if __IPHONE_5_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
UIKeyboardTypeTwitter, // A type optimized for twitter text entry (easy access to @ #)
#endif
UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated
};
18.
autocapitalizationType屬性:設置首字母大寫的類型。取值有以下幾種:
typedef NS_ENUM(NSInteger, UITextAutocapitalizationType) {
UITextAutocapitalizationTypeNone, // 不大寫
UITextAutocapitalizationTypeWords, // 單詞首字母大寫
UITextAutocapitalizationTypeSentences, // 句子首字母大寫
UITextAutocapitalizationTypeAllCharacters, // 所有字母大寫
};
19.
returnKeyType屬性:設置輸入完畢,按return鍵時的操作。
typedef NS_ENUM(NSInteger, UIReturnKeyType) {
UIReturnKeyDefault, // 默認 灰色按鈕,標有Return
UIReturnKeyGo, // 標有Go的藍色按鈕
UIReturnKeyGoogle, // 標有Google的藍色按鈕,用於搜索
UIReturnKeyJoin, // 標有Join的藍色按鈕
UIReturnKeyNext, // 標有Next的藍色按鈕
UIReturnKeyRoute, // 標有Route的藍色按鈕
UIReturnKeySearch, // 標有Search的藍色按鈕
UIReturnKeySend, // 標有Send的藍色按鈕
UIReturnKeyYahoo, // 標有Yahoo的藍色按鈕
UIReturnKeyDone, // 標有Done的藍色按鈕
UIReturnKeyEmergencyCall, // 緊急呼叫按鈕
};
這里僅僅演示UIReturnKeyGo樣式:

keyboardAppearance屬性:設置鍵盤外觀,取值有以下幾種:
typedef NS_ENUM(NSInteger, UIKeyboardAppearance) {
UIKeyboardAppearanceDefault,
// Default apperance for the current input method. 默認外觀,淺灰色
UIKeyboardAppearanceAlert
// Appearance suitable for use in "alert" scenarios. 深灰 石墨色
};
21.
delegate屬性:設置代理,其值為
id<UITextViewDelegate>類型,其中包含對UITextField操作的以下方法:
@protocol UITextViewDelegate <NSObject, UIScrollViewDelegate> @optional - (BOOL)textViewShouldBeginEditing:(UITextView *)textView; - (BOOL)textViewShouldEndEditing:(UITextView *)textView; - (void)textViewDidBeginEditing:(UITextView *)textView; - (void)textViewDidEndEditing:(UITextView *)textView; - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; - (void)textViewDidChange:(UITextView *)textView; - (void)textViewDidChangeSelection:(UITextView *)textView; @end22.
rightView和
leftView屬性:設置最右側\左側加圖片。
23.
rightViewMode和
leftViewMode屬性:設置最右側\左側加圖片顯示類型,這里有個設置右側圖片的例子,左側的類似:
UIImageView *image=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"010.png"]]; textField.rightView=image; textField.rightViewMode = UITextFieldViewModeAlways; [self.view addSubview:textField];24.
inputView屬性:設置一個UIView類型的自定義鍵盤。
25.
inputAccessoryView屬性:設置一個鍵盤的自定義工具條。
UITextField控件的常用方法
這一部分包括UITextField的類\對象方法和委托方法:UITextField的類\對象方法
UITextField的常用方法主要是重寫繪制行為的一些方法,除了UITextField對象的風格選項,你還可以定制化UITextField對象,為他添加許多不同的重寫方法,來改變文本字段的顯示行為。這些方法都會返回一個CGRect結構,制定了文本字段每個部件的邊界范圍。以下方法都可以重寫。
// drawing and positioning overrides - (CGRect)borderRectForBounds:(CGRect)bounds; // 重寫來重置邊緣區域 - (CGRect)textRectForBounds:(CGRect)bounds; // 重寫來重置文字區域 - (CGRect)placeholderRectForBounds:(CGRect)bounds; // 重寫來重置占位符區域 - (CGRect)editingRectForBounds:(CGRect)bounds; // 重寫來重置編輯區域 - (CGRect)clearButtonRectForBounds:(CGRect)bounds; // 重寫來重置clearButton位置,改變size可能導致button的圖片失真 - (CGRect)leftViewRectForBounds:(CGRect)bounds; - (CGRect)rightViewRectForBounds:(CGRect)bounds; - (void)drawTextInRect:(CGRect)rect; // 改變繪文字屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了. - (void)drawPlaceholderInRect:(CGRect)rect; // 重寫改變繪制占位符屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了.
UITextField的委托方法
UITextField的委托方法主要是用於鍵盤的輸入處理的@protocol UITextFieldDelegate @optional - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing. - (void)textFieldDidBeginEditing:(UITextField *)textField; // became first responder - (BOOL)textFieldShouldEndEditing:(UITextField *)textField; // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end - (void)textFieldDidEndEditing:(UITextField *)textField; // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text - (BOOL)textFieldShouldClear:(UITextField *)textField; // called when clear button pressed. return NO to ignore (no notifications) - (BOOL)textFieldShouldReturn:(UITextField *)textField; // called when 'return' key pressed. return NO to ignore. @end
UITextField支持的事件
UITextField派生自UIControl,所以UIControl類中的通知系統在文本字段中也可以使用。 除了UIControl類的標准事件,還可以使用下列UITextField類特有的事件
UIKIT_EXTERN NSString *const UITextFieldTextDidBeginEditingNotification; UIKIT_EXTERN NSString *const UITextFieldTextDidEndEditingNotification; UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;
當文本字段退出編輯模式時觸發。通知的object屬性存儲了最終文本。 因為文本字段要使用鍵盤輸入文字,所以下面這些事件發生時,也會發送動作通知
UIKeyboardWillShowNotification //鍵盤顯示之前發送 UIKeyboardDidShowNotification //鍵盤顯示之后發送 UIKeyboardWillHideNotification //鍵盤隱藏之前發送 UIKeyboardDidHideNotification //鍵盤隱藏之后發送
1_2.文本視圖UITextView
文本視圖UITextView與文本框類似,差別在於文本視圖可現實一個可滾動的文本塊。僅當需要的輸入內容很多時,才使用文本視圖。UITextView常用的屬性
在剛才使用的大篇幅介紹的UITextField的屬性大部分與UITextView是通用的,下面是一些UITextView的特有的屬性: 1.selectedRange屬性:設置被選中的字符的Range,一般在編輯功能代碼中使用。
2.
editable屬性:設置是否可編輯。
3.
dataDetectorTypes屬性:設置數據檢測類型。其值為以下幾種:
typedef NS_OPTIONS(NSUInteger, UIDataDetectorTypes) {
UIDataDetectorTypePhoneNumber = 1 << 0, // Phone number detection
UIDataDetectorTypeLink = 1 << 1, // URL detection
#if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
UIDataDetectorTypeAddress = 1 << 2, // Street address detection
UIDataDetectorTypeCalendarEvent = 1 << 3, // Event detection
#endif
UIDataDetectorTypeNone = 0, // No detection at all
UIDataDetectorTypeAll = NSUIntegerMax // All types
};
4.
allowsEditingTextAttributes屬性:設置。。。??。
5.
attributedText屬性:設置。。。??。
6.
typingAttributes屬性:設置。。。??。
7.
delegate屬性:是
id<UITextViewDelegate>類型。
UITextView常用的方法
UITextView的類\對象方法
UITextView繼承了UIScrollView,並且遵守UITextInput協議,因而具有它們中包含的方法,但還有一些特有的方法:- (BOOL)hasText; - (void)scrollRangeToVisible:(NSRange)range;
UITextView的委托方法
UITextView委托遵守了UITextViewDelegate協議,UITextViewDelegate協議又遵守了UIScrollViewDelegate協議,它具有以下方法:
@protocol UITextViewDelegate <NSObject, UIScrollViewDelegate> @optional - (BOOL)textViewShouldBeginEditing:(UITextView *)textView; - (BOOL)textViewShouldEndEditing:(UITextView *)textView; - (void)textViewDidBeginEditing:(UITextView *)textView; - (void)textViewDidEndEditing:(UITextView *)textView; - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; - (void)textViewDidChange:(UITextView *)textView; - (void)textViewDidChangeSelection:(UITextView *)textView; @end
UITextView支持的事件
UITextView支持UIControl中定義的事件。1_3.鍵盤輸入的處理程序
2.標簽UILabel和按鈕UIButton
UILabel標簽控件常用於標識一些信息,UIButton常用於完成一些動作。2_1.標簽UILabel
UILabel常見的屬性
1.shadowColor屬性:設置陰影顏色 。
2.
shadowOffset屬性:設置陰影偏移量。
3.
lineBreakMode屬性:設置文字過長時的顯示格式。取值有以下幾種:
typedef NS_ENUM(NSInteger, NSLineBreakMode) { /* What to do with long lines */
NSLineBreakByWordWrapping = 0, /* 單詞為顯示單位顯示,后面部分省略不顯示。 */
NSLineBreakByCharWrapping, /* 以字符為顯示單位顯示,后面部分省略不顯示。 */
NSLineBreakByClipping, /* 剪切與文本寬度相同的內容長度,后半部分被刪除。*/
NSLineBreakByTruncatingHead, /* 前面部分文字以……方式省略,顯示尾部文字內容。 */
NSLineBreakByTruncatingTail, /* 結尾部分的內容以……方式省略,顯示頭的文字內容。 */
NSLineBreakByTruncatingMiddle /* 中間的內容以……方式省略,顯示頭尾的文字內容 */
} NS_ENUM_AVAILABLE_IOS(6_0);
4.
attributedText屬性:設置標簽屬性文本。
5.
highlightedTextColor屬性:設置高亮顯示時的文本顏色。
6.
highlighted屬性:設置是否高亮顯示。
7.
userInteractionEnabled屬性:設置是否能與用戶交互。
8.
enabled屬性:只是決定了Label的繪制方式,將它設置為NO將會使文本變暗,表示它沒有激活,這時向它設置顏色值是無效的。
9.
numberOfLines屬性:設置文本最多行數,為0時沒有最大行數限制。
10.
adjustsLetterSpacingToFitWidth屬性:設置改變字母之間的間距來適應Label大小。
// default is NO, adjust letter spacing to make text fit. Note: setting this property to YES will cause the value of -[NSParagraphStyle tighteningFactorForTruncation] to be disgregarded.11.
minimumFontSize屬性:設置最小收縮字號,如果Label寬度小於文字長度時,文字字號減小,低於設定字號后,不再減小。6.0以后不再使用了。
12.
baselineAdjustment屬性:設置文本的基線位置,只有文本行數為1是有效。取值有以下幾種:
typedef NS_ENUM(NSInteger, UIBaselineAdjustment) {
UIBaselineAdjustmentAlignBaselines = 0, // 默認值文本最上端於label中線對齊
UIBaselineAdjustmentAlignCenters, // 文本中線於label中線對齊
UIBaselineAdjustmentNone, // 文本最低端與label中線對齊
};
13.
minimumScaleFactor屬性:設置最小收縮比例,如果Label寬度小於文字長度時,文字進行收縮,收縮超過比例后,停止收縮。
14.
preferredMaxLayoutWidth屬性:設置preferredMaxLayoutWidth,autolayout才會判斷到折行的位置。知道一個確切的width當然是最好的,那么直接設置即可,但是如果UILabel的寬度是自適應的,不確定,那么可以使用如下的代碼設置
- (void)layoutSubViews
{
[super layoutSubViews];
self.label.preferredMaxLayoutWidth = self.label.bounds.size.width;
}
15.
autoShrink屬性:設置是否自動收縮。Fixed Font Size 默認,如果Label寬度小於文字長度時時,文字大小不自動縮放minimumScaleFactor 設置最小收縮比例,如果Label寬度小於文字長度時,文字進行收縮,收縮超過比例后,停止收縮。minimumFontSize設置最小收縮字號,如果Label寬度小於文字長度時,文字字號 減小,低於設定字號后,不再減小。6.0以后不再使用了。
UILabel常用的方法
UILabel的類\對象方法
UILabel繼承自UIView並且遵守<NSCoding>協議,包含來自他們的方法,還有一些獨有方法:- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines; // 計算numberOfLines行后的Label的Frame - (void)drawTextInRect:(CGRect)rect; //改變繪文字屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了.
UILabel的委托方法(不存在delegate屬性,無委托方法)
UILabel不存在delegate屬性,無委托方法。
UILabel支持的事件
。。UILabel開發中常見的功能
UILabel 多行文字自動換行 (自動折行)
UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 300, 180)]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 150)]; label.text = @"where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you?"; //清空背景顏色 label.backgroundColor = [UIColor clearColor]; //設置字體顏色為白色 label.textColor = [UIColor whiteColor]; //文字居中顯示 label.textAlignment = UITextAlignmentCenter; //自動折行設置 label.lineBreakMode = UILineBreakModeWordWrap; label.numberOfLines = 0;
2_2.按鈕UIButton
UIButton的常見屬性
1.contentEdgeInsets屬性:設置調整按鈕的邊間距---整個內容的邊間距。其取值有以下幾種:
typedef struct UIEdgeInsets {
CGFloat top, left, bottom, right; // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;
2.
titleEdgeInsets屬性:設置調整按鈕的邊間距---標題設置。
3.
imageEdgeInsets屬性:設置調整按鈕的邊間距---圖片設置。
4.
reversesTitleShadowWhenHighlighted屬性:設置按鈕高亮時是否改變陰影.默認時NO,當為YES時,陰影在雕刻與浮雕感之間變化。
5.
adjustsImageWhenHighlighted屬性:設置當按鈕高亮時圖片是否改變,為真時圖片隨按鈕高亮而高亮。
6.
adjustsImageWhenDisabled屬性:設置當按鈕高亮時圖片是否改變,為真時圖片隨按鈕失效而變暗。
7.
showsTouchWhenHighlighted屬性:設置當按鈕按下時是否閃光.默認NO,YES時按下會有白色光點.圖片和按鈕事件的不會因閃光改變。
8.
tintColor屬性:非公開的按鈕風格,改變按鈕顏色。
9.
buttonType屬性:只讀,獲得按鈕類型。
10.
currentTitle屬性:只讀,獲得當前title。
11.
currentTitleColor屬性:只讀,獲得當前title的顏色,默認white(1,1)。
12.
currentTitleShadowColor屬性:只讀,獲得標題的陰影顏色,默認white(0,0.5)。
13.
currentImage屬性:只讀,獲得當前按鈕上的圖片,可以是nil。
14.
currentBackgroundImage屬性:只讀,當前按鈕背景圖片,可以是nil。
15.
currentAttributedTitle屬性:只讀,當前屬性標題。
16.
titleLabel屬性:只讀,顯示按鈕當前標題的視圖,雖然它是只讀的,但是它的屬性是可讀寫的.它的屬性在按鈕還沒有顯示之前就有返回值.系統按鈕這些值為nil。。
17.
imageView屬性:只讀, 按鈕上的圖片視圖(只讀).雖然它是只讀的,但是他的屬性是可讀寫的.imageView的屬性在按鈕還沒有顯示前就有值了.系統按鈕這些值是nil。。
18.
lineBreakMode屬性:property Deprecated in iOS 3.0。
19.
titleShadowOffset屬性:property Deprecated in iOS 3.0。
UIButton常用的方法
UIButton的類\對象方法
快速創建方法:+ (id)buttonWithType:(UIButtonType)buttonType;參數buttonType的取值有以下幾種:
typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0, // no button type
UIButtonTypeRoundedRect, // rounded rect, flat white button, like in address card
UIButtonTypeDetailDisclosure, // 一個詳細披露按鈕
UIButtonTypeInfoLight, // 淺色背景的信息按鈕
UIButtonTypeInfoDark, // 黑暗背景的信息按鈕
UIButtonTypeContactAdd, // 一個聯系人添加“按鈕
};
setter:
- (void)setTitle:(NSString *)title forState:(UIControlState)state; // default is nil. title is assumed to be single line - (void)setTitleColor:(UIColor *)color forState:(UIControlState)state; // default if nil. use opaque white - (void)setTitleShadowColor:(UIColor *)color forState:(UIControlState)state; // default is nil. use 50% black - (void)setImage:(UIImage *)image forState:(UIControlState)state; // default is nil. should be same size if different for different states - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state; // default is nil - (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state NS_AVAILABLE_IOS(6_0); // default is nil. title is assumed to be single linegetter:
- (NSString *)titleForState:(UIControlState)state; // these getters only take a single state value - (UIColor *)titleColorForState:(UIControlState)state; - (UIColor *)titleShadowColorForState:(UIControlState)state; - (UIImage *)imageForState:(UIControlState)state; - (UIImage *)backgroundImageForState:(UIControlState)state; - (NSAttributedString *)attributedTitleForState:(UIControlState)state NS_AVAILABLE_IOS(6_0);重寫繪制行為:
- (CGRect)backgroundRectForBounds:(CGRect)bounds; // 指定背景邊界 - (CGRect)contentRectForBounds:(CGRect)bounds; // 指定內容邊界 - (CGRect)titleRectForContentRect:(CGRect)contentRect; // 指定文字標題邊界 - (CGRect)imageRectForContentRect:(CGRect)contentRect; // 指定按鈕圖像邊界
UIButton的委托方法(UIButton沒有delegate屬性,無委托方法)
UIButton沒有delegate屬性,無委托方法
UIButton支持的事件
除了UIControl中繼承的事件,無其他事件。
UIButton在開發中常見的功能
。。。。。。。3.滑塊UISlider、步進UIStepper和圖像UIImageView
。。。。。。。。。。。。。。3_1.滑塊UISlider
UISlider的常見屬性
1.value屬性:設置/讀取滑塊的值。
2.
minimumValue屬性:設置可變的最小值。
3.
maximumValue屬性:設置可變的最大值。
4.
minimumValueImage屬性:設置最小值的圖片。
5.
maximumValueImage屬性:設置最大值的圖片。
6.
continuous屬性:默認為YES,設置為YES時,只要滑輪滾動機會觸發change方法;設置為NO時,只有滑輪停止移動時,才會觸發change方法。
7.
minimumTrackTintColor屬性:設置已經滑過一端滑動條(滑輪左邊)顏色。如果設置了,左邊的圖片就不會顯示.
8.
maximumTrackTintColor屬性:設置未滑過一端滑動條(滑輪右邊)顏色。如果設置了,右邊的圖片就不會顯示
9.
thumbTintColor屬性:設置滑輪的顏色,如果設置了,滑輪的樣式圖片就不會顯示。
10.
currentThumbImage屬性:只讀,獲得當前換輪的圖片。
11.
currentMinimumTrackImage屬性:只讀,獲得當前滑塊左邊的圖片。
12.
currentMaximumTrackImage屬性:只讀,獲得當前滑塊右邊的圖片。
UISlider的常用方法
UISlider的類\對象方法
setter:
- (void)setValue:(float)value animated:(BOOL)animated; // move slider at fixed velocity (i.e. duration depends on distance). does not send action // set the images for the slider. there are 3, the thumb which is centered by default and the track. You can specify different left and right track // e.g blue on the left as you increase and white to the right of the thumb. The track images should be 3 part resizable (via UIImage's resizableImage methods) along the direction that is longer - (void)setThumbImage:(UIImage *)image forState:(UIControlState)state; - (void)setMinimumTrackImage:(UIImage *)image forState:(UIControlState)state; - (void)setMaximumTrackImage:(UIImage *)image forState:(UIControlState)state;
getter:
- (UIImage *)thumbImageForState:(UIControlState)state; - (UIImage *)minimumTrackImageForState:(UIControlState)state; - (UIImage *)maximumTrackImageForState:(UIControlState)state;
重寫繪圖行為:
// lets a subclass lay out the track and thumb as needed - (CGRect)minimumValueImageRectForBounds:(CGRect)bounds; - (CGRect)maximumValueImageRectForBounds:(CGRect)bounds; - (CGRect)trackRectForBounds:(CGRect)bounds; - (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value;
UISlider的委托方法(UISlider沒有delegate屬性,無委托方法)
UISlider沒有delegate屬性,無委托方法
UISlider支持的事件
支持的所有事件來自UIControl,常用的有UIControlEventValueChanged事件。3_2.步進UIStepper
UIStepper的常見屬性
1.continuous屬性:設置是否立刻發送ValueChange事件。默認YES,YES時表示當用戶交互時會立刻發送ValueChange事件,NO則是只有等用戶交互結束時
2.
autorepeat屬性:默認YES,YES時表示按住加號或減號不松手,數值會持續變化。
3.
wraps屬性:設置值是否在[minimumValue,maximumValue]區間內循環。默認NO,設置YES時,當value加的超過maximumValue,value將變成minimumValue的值
4.
value屬性:設置當前值,默認是0,上限是maximumValue,下限是minimumValue,當數值改變時,會發送UIControlValueEventChanged給目標。
5.
minimumValue屬性:設置最小值。
6.
maximumValue屬性:設置最大值。
7.
stepValue屬性:設置步長。
8.
tintColor屬性:設置控件顏色,注意tintColor是控件的顏色,而backGroundColor是空間背景(frame)的顏色。
UIStepper的常用方法
UIStepper的類\對象方法
setter and getter:
// a background image which will be 3-way stretched over the whole of the control. Each half of the stepper will paint the image appropriate for its state - (void)setBackgroundImage:(UIImage*)image forState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; - (UIImage*)backgroundImageForState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; // an image which will be painted in between the two stepper segments. The image is selected depending both segments' state - (void)setDividerImage:(UIImage*)image forLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; - (UIImage*)dividerImageForLeftSegmentState:(UIControlState)state rightSegmentState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; // the glyph image for the plus/increase button - (void)setIncrementImage:(UIImage *)image forState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; - (UIImage *)incrementImageForState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; // the glyph image for the minus/decrease button - (void)setDecrementImage:(UIImage *)image forState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; - (UIImage *)decrementImageForState:(UIControlState)state NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
UIStepper委托方法(UIStepper沒有delegate屬性,無委托方法)
UIStepper支持的事件
UIStepper支持的事件來自UIControl,常用的事件是UIControlEventValueChanged。3_3.圖像UIImageView
UIImageView的常見屬性
1.image屬性:設置圖片,默認顯示。
2.
highlightedImage屬性:設置高亮狀態下顯示的圖片。
3.
userInteractionEnabled屬性:設置是否允許用戶交互,默認不允許。
4.
highlighted屬性:設置是否為高亮狀態,默認為普通狀態。
5.
animationImages屬性:設置序列幀動畫的圖片數組NSArray*。
6.
highlightedAnimationImages屬性:設置高亮狀態下序列幀動畫的圖片數組。
7.
animationDuration屬性:設置序列幀動畫播放的時長。
8.
animationRepeatCount屬性:設置序列幀動畫播放的次數。
UIImageView的常用方法
UIImageView的類\對象方法
構造方法:- (id)initWithImage:(UIImage *)image; - (id)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage NS_AVAILABLE_IOS(3_0);圖片幀動畫控制方法:
- (void)startAnimating; - (void)stopAnimating; - (BOOL)isAnimating;
UIImageView的委托方法(UIImageView沒有delegate屬性,無委托方法)
UIImageView支持的事件
UIImageView不支持任何事件UIImageView開發中常用的功能
將圖片數組按照順序播放形成序列幀動畫
NSArray *magesArray = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image1.png"],
[UIImage imageNamed:@"image2.png"],
[UIImage imageNamed:@"image3.png"],
[UIImage imageNamed:@"image4.png"],
[UIImage imageNamed:@"image5.png"],nil];
UIImageView *animationImageView = [UIImageView alloc]init];
[animationImageView initWithFrame:CGRectMake(0, 0, 131, 125)];
animationImageView.animationImages = imagesArray;//將序列幀數組賦給UIImageView的animationImages屬性
animationImageView.animationDuration = 0.25;//設置動畫時間
animationImageView.animationRepeatCount = 0;//設置動畫次數 0 表示無限
[animationImageView startAnimating];//開始播放動畫
3_4.圖片瀏覽器
本例是做一個界面如下的圖片瀏覽器:
當滑動滑動時圖片會變化,在圖集中的順序(5/10)也相應的變化.過程如下:
首先向storyboard的view中添加一個UIlabel控件、一個UIImageView控件、一個UISlider控件並調整好位置。
然后將三個空間connect為ViewController的三個屬性:lbl、imgView和slider.為UISlider控件connect方法sliderChange
在ViewController.h中
@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *lbl; @property (weak, nonatomic) IBOutlet UIImageView *imgView; @property (weak, nonatomic) IBOutlet UISlider *slider; - (IBAction)sliderChange; @end
在ViewController.m中
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_slider.minimumValue = 1;
_slider.maximumValue = 10;
}
- (IBAction)sliderChange{
int curIndex = (int)_slider.value;
_lbl.text = [NSString stringWithFormat:@"%d/10", curIndex];
_imgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%02d.png", curIndex]]; // 圖片序列為01.png 02.png......10.png
}
@end
4.開關控件UISwitch和分段控件UISegmentedControl
4_1.開關控件UISwitch
.....
UISwitch的常見屬性
1.onTintColor屬性:設置ON一邊的背景顏色,默認是綠色。
2.
tintColor屬性:設置OFF一邊的背景顏色,默認是灰色,發現OFF背景顏色其實也是控件”邊框“顏色。
3.
thumbTintColor屬性:設置滑塊顏色。
4.
onImage屬性:設置ON的image。
5.
offImage屬性:設置OFF的image。
6.
on屬性:是否處於ON狀態。
UISwitch的常用方法
UISwitch的類\對象方法
構造方法:
- (id)initWithFrame:(CGRect)frame;
其他方法:
- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action 設置ON/OFF狀態
UISwitch的委托方法(UISwitch沒有delegate屬性,無委托方法)
UISwitch支持的事件
事件來自UIControl,常用的事件為UIControlEventValueChanged。
UISwitch在開發中常用的功能
4_2.分段控件UISegmentedControl
UISegmentedControl常見的屬性/span>
1.segmentedControlStyle屬性:設置基本的樣式。取值有下面幾種:
typedef NS_ENUM(NSInteger, UISegmentedControlStyle) {
UISegmentedControlStylePlain, // large plain
UISegmentedControlStyleBordered, // large bordered
UISegmentedControlStyleBar, // small button/nav bar style. tintable
UISegmentedControlStyleBezeled, // DEPRECATED. Do not use this style.
};
演示效果如下:

momentary屬性:設置在點擊后是否恢復原樣 。
3.
numberOfSegments屬性:只讀,獲取總選項數。
4.
apportionsSegmentWidthsByContent屬性:設置是否根據segment的內容改變segment的寬度,默認為NO,寬度相同。
5.
selectedSegmentIndex屬性:設置選中第幾個segment,一般用於初始化時選中。
6.
tintColor屬性:設置控件顏色,當為Bordered和Bar時tintColor才有效。
UISegmentedControl常用的方法
UISegmentedControl的類\對象方法
構造方法:
- (id)initWithItems:(NSArray *)items; // items can be NSStrings or UIImages. control is automatically sized to fit content
功能方法:
- (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated; // insert before segment number. 0..#segments. value pinned - (void)insertSegmentWithImage:(UIImage *)image atIndex:(NSUInteger)segment animated:(BOOL)animated; - (void)removeSegmentAtIndex:(NSUInteger)segment animated:(BOOL)animated; - (void)removeAllSegments;
setter和getter:
- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment; // default is nil - (NSString *)titleForSegmentAtIndex:(NSUInteger)segment; - (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)segment; // default is nil - (UIImage *)imageForSegmentAtIndex:(NSUInteger)segment; - (void)setWidth:(CGFloat)width forSegmentAtIndex:(NSUInteger)segment; // set to 0.0 width to autosize. default is 0.0 - (CGFloat)widthForSegmentAtIndex:(NSUInteger)segment; - (void)setContentOffset:(CGSize)offset forSegmentAtIndex:(NSUInteger)segment; // adjust offset of image or text.default is (0,0) - (CGSize)contentOffsetForSegmentAtIndex:(NSUInteger)segment; - (void)setEnabled:(BOOL)enabled forSegmentAtIndex:(NSUInteger)segment; // default is YES - (BOOL)isEnabledForSegmentAtIndex:(NSUInteger)segment; - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics; - (UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics; - (void)setDividerImage:(UIImage *)dividerImage forLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState barMetrics:(UIBarMetrics)barMetrics; - (UIImage *)dividerImageForLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState barMetrics:(UIBarMetrics)barMetrics; - (void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state; - (NSDictionary *)titleTextAttributesForState:(UIControlState)state; - (void)setContentPositionAdjustment:(UIOffset)adjustment forSegmentType:(UISegmentedControlSegment)leftCenterRightOrAlone barMetrics:(UIBarMetrics)barMetrics; - (UIOffset)contentPositionAdjustmentForSegmentType:(UISegmentedControlSegment)leftCenterRightOrAlone barMetrics:(UIBarMetrics)barMetrics;
UISegmentedControl的委托方法(UISegmentControl沒有delegate屬性,無委托方法)
UISegmentedControl支持的事件
常用的事件為UIControlEventValueChanged。4_3.圖片排序
有這樣的場景,程序運行后的界面如下:

先搭建界面連接UISegmentedControl的UIControlEventValueChanged事件處理為方法indexChange:(UISegmentedControl *)sender
ViewController.m中的代碼如下:
#import "ViewController.h"
#define kImgW 60
#define kImgH 60
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self adjustImagePosWithColumns:2 initFlag:YES]; // 界面初始化
}
#pragma mark Method:點擊了segment 更改圖片的列數
- (IBAction)indexChange:(UISegmentedControl *)sender {
int columns = sender.selectedSegmentIndex + 2;
[UIView beginAnimations:nil context:nil];
[self adjustImagePosWithColumns:columns initFlag:NO]; // 調整圖片的排列位置
[UIView commitAnimations];
}
#pragma mark Method:調整位置
- (void) adjustImagePosWithColumns:(int)columns initFlag:(BOOL)initFlag
{
// 1. 定義列數和間距
// 每個圖片之間的間距 = (控制器view的寬度 - 列數 * 表情的寬度) / (列數 + 1)
CGFloat margin = (self.view.frame.size.width - columns * kImgW) / (columns + 1);
// 2.定義第一個圖片的位置
// 第一個圖片的Y值
CGFloat oneY = 100;
// 第一個圖片的X值
CGFloat oneX = margin;
// 3.調整所有的圖片
for (int i = 0; i < 9; i++)
{
// 取出i位置的ImageView
int row = i / columns;
int col = i % columns;
CGFloat x = oneX + (kImgH + margin) * col; // 新的x
CGFloat y = oneY + (kImgH + margin) * row; // 新的y
if (initFlag){ // 如果是initFlag == YES 則進行界面的初始化,將所有的圖片添加到view
[self addImage:[NSString stringWithFormat:@"01%d.gif", i] x:x y:y];
}else{ // initFlag == NO 進行調整位置、重新排列
UIView *child = self.view.subviews[i+1]; // i+1 去掉第一個控件UISegmentedControl
CGRect tempFrame = child.frame;
tempFrame.origin.x = x;
tempFrame.origin.y = y;
child.frame = tempFrame;
}
}
}
#pragma mark Method:添加圖片
- (void)addImage:(NSString *)icon x:(CGFloat)x y:(CGFloat)y{
UIImageView *img = [[UIImageView alloc] init];
img.image = [UIImage imageNamed:icon];
img.frame = CGRectMake(x, y, kImgW, kImgH);
[self.view addSubview:img];
}
@end
5.工具欄UIToolBar
5_1.工具欄UIToolBar的使用
UIToolBar的常見屬性
1.barStyle屬性:設置toolbar的外觀風格。取值有以下幾種:
typedef NS_ENUM(NSInteger, UIBarStyle) {
UIBarStyleDefault = 0,
UIBarStyleBlack = 1,
UIBarStyleBlackOpaque = 1, // Deprecated. Use UIBarStyleBlack
UIBarStyleBlackTranslucent = 2, // Deprecated. Use UIBarStyleBlack and set the translucent property to YES
};

items屬性:設置/獲取所有的UIBarButtonItem組成的數組。
3.
translucent屬性:設置是否為半透明。默認的值是NO,如果barStyle設置為UIBarStyleBlackTranslucent,其值始終是YES。
4.
tintColor屬性:設置。。。。默認值為nil。
UIToolBar的常用方法
UIToolBar的類\對象方法
setter和getter
- (void)setItems:(NSArray *)items animated:(BOOL)animated; - (void)setBackgroundImage:(UIImage *)backgroundImage forToolbarPosition:(UIToolbarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR; - (UIImage *)backgroundImageForToolbarPosition:(UIToolbarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR; - (void)setShadowImage:(UIImage *)shadowImage forToolbarPosition:(UIToolbarPosition)topOrBottom NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; - (UIImage *)shadowImageForToolbarPosition:(UIToolbarPosition)topOrBottom NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
UIToolBar的委托方法(UIToolBar沒有delegate屬性,無委托方法)
UIToolBar支持的事件(UIToolBar事件依賴於它的內部控件BarButtonItem,它自己不支持任何事件)
5_2.UIBarButtonItem
UIToolBar內部的控件都被包裝成了UIBarButtonItem類型,因此UIBarButtonItem也就具有較多的屬性和功能:UIBarButtonItem的常見屬性
1.style屬性:設置UIBarButtonItem外觀風格。其值有以下幾種:
typedef NS_ENUM(NSInteger, UIBarButtonItemStyle) {
UIBarButtonItemStylePlain, // 顯示為純文本 但是shows glow when pressed
UIBarButtonItemStyleBordered, // 默認樣式
UIBarButtonItemStyleDone, // 深藍色的選中顏色
};
2.
possibleTitles屬性:設置(暫時不知它的用法)。
3.
customView屬性:設置自定義的item視圖,一般傳遞一個UIButton。
4.
action屬性:設置進行事件處理的方法。
5.
target屬性:設置進行事件處理的控制器實例。
在開發中經常會設置UIBarButtonSystemItem,使item有不同的圖標它的取值有以下幾種:

1.
UIBarButtonSystemItemFlexibleSpace:靈活的空間。將toolbar中剩余的空間充滿,但是不會有圖標,效果為透明色。
2.
UIBarButtonSystemItemFixedSpace:填充的空間。通過拉伸該類型的item自由分配toolbar的剩余空間,但是不會有圖標,效果為透明色。
UIBarButtonItem的常用方法
UIBarButtonItem的類\對象方法
構造方法:
- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action; - (id)initWithImage:(UIImage *)image landscapeImagePhone:(UIImage *)landscapeImagePhone style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action NS_AVAILABLE_IOS(5_0); - (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action; - (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action; - (id)initWithCustomView:(UIView *)customView;
setter和getter:
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics; - (UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics; /* This sets the background image for buttons with a specific style. When calling this on a UIBarButtonItem instance, the style argument must match the button's style; when calling on the UIAppearance proxy, any style may be passed. */ - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state style:(UIBarButtonItemStyle)style barMetrics:(UIBarMetrics)barMetrics; - (UIImage *)backgroundImageForState:(UIControlState)state style:(UIBarButtonItemStyle)style barMetrics:(UIBarMetrics)barMetrics; /* For adjusting the vertical centering of bordered bar buttons within the bar */ - (void)setBackgroundVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR; - (CGFloat)backgroundVerticalPositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR; /* For adjusting the position of a title (if any) within a bordered bar button */ - (void)setTitlePositionAdjustment:(UIOffset)adjustment forBarMetrics:(UIBarMetrics)barMetrics; - (UIOffset)titlePositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics; /* The remaining appearance modifiers apply solely to UINavigationBar back buttons and are ignored by other buttons. */ /* backgroundImage must be a resizable image for good results. */ - (void)setBackButtonBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics; - (UIImage *)backButtonBackgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics; - (void)setBackButtonTitlePositionAdjustment:(UIOffset)adjustment forBarMetrics:(UIBarMetrics)barMetrics; - (UIOffset)backButtonTitlePositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics; /* For adjusting the vertical centering of bordered bar buttons within the bar */ - (void)setBackButtonBackgroundVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics; - (CGFloat)backButtonBackgroundVerticalPositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics;
