以下整理九個在 iOS 開發中經常需要翻查的實用知識點,從 ScrollView 的三個關鍵屬性到鍵盤工具列的自訂封裝。
contentSize 代表 scrollView 中可顯示區域的整體大小。假設一個 scrollView 的 frame 為 (0, 0, 320, 480),而 contentSize 為 (320, 960),代表整個內容高 960,必須上下滑動才能看到後面 480 的部分。
contentOffset 是目前顯示區域頂點相對於 frame 頂點的偏移量。以上例而言,滑到最底部時 contentOffset 就是 (0, -480),也就是 Y 軸偏移了 480。
contentInset 是 contentView 與 scrollView 原點之間的關係。例如 contentView 的 frame 為 (0, 30, 320, 480),則 contentInset 為 (0, 30),可分別設定上下左右。
以下載 iOS 7.0 模擬器為例:開啟 ios_7_0_simulator.dmg 後可看到 iPhoneSimulatorSDK7_0.pkg,安裝後預設位於所選磁碟區的 /Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk。完全結束 Xcode 後,把該目錄複製到 /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/ 即可(Xcode.app 可「顯示套件內容」)。重啟 Xcode 就能使用該版本模擬器。更簡單的方式是直接從舊版 Xcode(如 5.0.2)複製已安裝好的模擬器目錄,位置完全相同,就不必再下載離線安裝包。
UITextField 與 UITextView 都有 inputAccessoryView 屬性,想在鍵盤上方顯示自訂 view 時就設定它,該 view 會自動跟著鍵盤一起出現。注意自訂的 view 不應處於其他視圖層之中,也不應是其他視圖的子視圖——只要賦值給這個屬性即可。inputView 則是鍵盤本體,為 nil 時顯示系統預設鍵盤。
實例一:為鍵盤加上工具列
- (void)createKeyboardTool {
keyboardTool = [[UIToolbar alloc] initWithFrame:CGRectMake(kZero, kZero, kScreenW, 44.0f)];
NSMutableArray *myToolBarItems = [NSMutableArray array];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemReply
target:self action:@selector(cancelAction)];
UIBarButtonItem *space = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self action:@selector(saveAction)];
UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:@selector(saveAction)];
[myToolBarItems addObject:cancelBtn];
[myToolBarItems addObject:space];
[myToolBarItems addObject:saveBtn];
keyboardTool.items = myToolBarItems;
}
commentTextView = [[UITextView alloc] initWithFrame:CGRectMake(kZero, kZero, kScreenW, 200)];
[commentTextView becomeFirstResponder];
commentTextView.inputAccessoryView = keyboardTool;
實例二:切換自訂鍵盤與系統鍵盤
/**
* 切換鍵盤
*/
- (void)switchKeyboard {
// self.textView.inputView == nil 代表目前使用系統內建鍵盤
if (self.textView.inputView == nil) {
self.textView.inputView = self.emotionKeyboard; // 切換為自訂表情鍵盤
self.toolbar.showKeyboardButton = YES;
} else {
self.textView.inputView = nil; // 切換回系統鍵盤
self.toolbar.showKeyboardButton = NO;
}
self.switchingKeybaord = YES;
[self.textView endEditing:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[self.textView becomeFirstResponder];
self.switchingKeybaord = NO;
});
}
/**
* 鍵盤 frame 改變時呼叫(顯示、隱藏等)
*/
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
if (self.switchingKeybaord) return;
NSDictionary *userInfo = notification.userInfo;
double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
[UIView animateWithDuration:duration animations:^{
// 工具列 Y 值 = 鍵盤 Y 值 - 工具列高度
if (keyboardF.origin.y > self.view.height) {
self.toolbar.y = self.view.height - self.toolbar.height;
} else {
self.toolbar.y = keyboardF.origin.y - self.toolbar.height;
}
}];
}
-(UISearchBar *)mySearchBar {
if (_mySearchBar == nil) {
_mySearchBar = [[UISearchBar alloc] init];
_mySearchBar.showsCancelButton = YES;
_mySearchBar.delegate = self;
[_mySearchBar sizeToFit];
[_mySearchBar setPlaceholder:@"請輸入"];
[_mySearchBar setY:20];
// 處理 cancel 的文字顯示
for (id item in [_mySearchBar subviews]) {
for (id cc in [item subviews]) {
if ([cc isKindOfClass:[UIButton class]]) {
UIButton *btn = (UIButton *)cc;
[btn setTitle:@"取消" forState:UIControlStateNormal];
}
}
}
}
return _mySearchBar;
}
/**
* 修改 cancel 的顯示文字,必先把 showsCancelButton 設為 YES
*/
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
searchBar.showsCancelButton = YES;
for (id item in [searchBar subviews]) {
for (id cc in [item subviews]) {
if ([cc isKindOfClass:[UIButton class]]) {
UIButton *btn = (UIButton *)cc;
[btn setTitle:@"取消" forState:UIControlStateNormal];
}
}
}
}
在子頁面用 [self.navigationController.view addSubview:self.mySearchBar] 加入控件後,返回時它不會自動移除,必須手動清掉,否則會疊在父頁面的導航列上:
(void)viewWillDisappear:(BOOL)animated {
[self.mySearchBar removeFromSuperview];
[super viewWillDisappear:animated];
}
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(viewTapped:)];
// 若沒有這一句,view 中的 Button 等可能無法觸發 TouchUpInside 事件
tapGr.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGr];
}
-(void)viewTapped:(UITapGestureRecognizer *)tapGr {
[self.myTextField resignFirstResponder];
}
在專案的 Targets → Build Phases → Compile Sources 中,為該第三方插件的 .m 檔加上 -fno-objc-arc 旗標即可。若是像 PLTexture **previewTextures; 這種雙星號寫法,在 ARC 下則需改為 PLTexture * __unsafe_unretained *previewTextures;。
- (void)setupToolbar {
IWComposeToolbar *toolbar = [[IWComposeToolbar alloc] init];
toolbar.delegate = self;
CGFloat toolbarH = 35;
CGFloat toolbarW = self.view.width;
CGFloat toolbarY = self.view.height - toolbarH;
toolbar.frame = CGRectMake(0, toolbarY, toolbarW, toolbarH);
[self.view addSubview:toolbar];
self.toolbar = toolbar;
// 鍵盤即將顯示或隱藏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
#pragma mark - 鍵盤處理
- (void)keyboardWillHide:(NSNotification *)note {
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
self.toolbar.transform = CGAffineTransformIdentity;
}];
}
- (void)keyboardWillShow:(NSNotification *)note {
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyboardH = keyboardF.size.height;
self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keyboardH);
}];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
放棄第一響應者用 [self.textView resignFirstResponder];。另外也可以監聽內容變化:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:textView];
.h 檔:
#import <UIKit/UIKit.h>
@class IWComposeToolbar;
typedef enum {
IWComposeToolbarButtonTypeCamera,
IWComposeToolbarButtonTypePicture,
IWComposeToolbarButtonTypeMention,
IWComposeToolbarButtonTypeTrend,
IWComposeToolbarButtonTypeEmotion
} IWComposeToolbarButtonType;
@protocol IWComposeToolbarDelegate <NSObject>
@optional
- (void)composeToolbar:(IWComposeToolbar *)toolbar didClickButton:(IWComposeToolbarButtonType)butonType;
@end
@interface IWComposeToolbar : UIView
@property (weak, nonatomic) id<IWComposeToolbarDelegate> delegate;
@end
.m 檔:
#import "IWComposeToolbar.h"
@implementation IWComposeToolbar
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 1. 設定背景
self.backgroundColor = [UIColor colorWithPatternImage:
[UIImage imageWithName:@"compose_toolbar_background"]];
// 2. 加入按鈕
[self addButtonWithIcon:@"compose_camerabutton_background"
highIcon:@"compose_camerabutton_background_highlighted"
tag:IWComposeToolbarButtonTypeCamera];
[self addButtonWithIcon:@"compose_toolbar_picture"
highIcon:@"compose_toolbar_picture_highlighted"
tag:IWComposeToolbarButtonTypePicture];
[self addButtonWithIcon:@"compose_mentionbutton_background"
highIcon:@"compose_mentionbutton_background_highlighted"
tag:IWComposeToolbarButtonTypeMention];
[self addButtonWithIcon:@"compose_trendbutton_background"
highIcon:@"compose_trendbutton_background_highlighted"
tag:IWComposeToolbarButtonTypeTrend];
[self addButtonWithIcon:@"compose_emoticonbutton_background"
highIcon:@"compose_emoticonbutton_background_highlighted"
tag:IWComposeToolbarButtonTypeEmotion];
}
return self;
}
- (void)addButtonWithIcon:(NSString *)icon
highIcon:(NSString *)highIcon
tag:(IWComposeToolbarButtonType)tag {
UIButton *button = [[UIButton alloc] init];
button.tag = tag;
[button setBackgroundImage:[UIImage imageWithName:icon]
forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageWithName:highIcon]
forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
/**
* 監聽按鈕點擊
*/
- (void)buttonClick:(UIButton *)button {
if ([self.delegate respondsToSelector:@selector(composeToolbar:didClickButton:)]) {
[self.delegate composeToolbar:self didClickButton:button.tag];
}
}
- (void)layoutSubviews {
[super layoutSubviews];
int count = self.subviews.count;
CGFloat buttonW = self.width / count;
CGFloat buttonH = self.height;
for (int i = 0; i < count; i++) {
UIButton *button = self.subviews[i];
button.frame = CGRectMake(buttonW * i, 0, buttonW, buttonH);
}
}
@end
這九則知識涵蓋了 ScrollView 佈局、鍵盤互動、搜尋列客製化與自訂元件封裝等常見場景。其中「鍵盤通知 + 動畫位移」與「inputAccessoryView」是互動品質的關鍵細節,而自訂 UIView 並透過 delegate 對外溝通,則是元件化的標準做法,值得作為自己專案工具列的起手式。