自訂鍵盤聽起來是個小功能,但要做到「橫豎屏都正常、常用表情記得住、元件能被重複使用」,牽涉的知識其實不少:MVC 分層、iOS 自動佈局、元件封裝、Block 回調、以及 CoreData(或 SQLite)持久化。本文把這些東西整合成一個完整的表情鍵盤。
目錄按自己對 MVC 的理解切分,目的是拋磚引玉:Face 放表情圖片資源,Model 封裝「讀取歷史表情」的資料層,View 放所有自訂元件(也就是鍵盤相關的視圖),Controller 負責把各元件組裝起來。

先看一下成品。以下是豎屏與橫屏的顯示效果——因為元件大量使用自動佈局,換到橫屏或更大的螢幕都不用改程式。常用表情是使用者用過的表情,存進 SQLite 後按時間倒序排列;more 則是留給後續擴充的接口。

自訂元件意味著 storyboard 用不上,所有視圖都得手寫。這麼做反而保證了元件的靈活性、降低耦合,團隊協作時也好共用。封裝時的原則是:把外部可能用到的接口預留出來,把該回傳的資料回傳出去。
FaceView 負責顯示一張表情圖。使用時傳入圖片與對應文字(例如【哈 哈】),點擊後透過 block 把 image 與文字回傳給上層。
// FaceView.h #import <UIKit/UIKit.h> // 宣告表情對應的 block,用於把點擊的表情圖片與文字傳到上層 typedef void (^FaceBlock)(UIImage *image, NSString *imageText); @interface FaceView : UIView @property (nonatomic, strong) NSString *imageText; // 圖片對應的文字 @property (nonatomic, strong) UIImage *headerImage; // 表情圖片 - (void)setFaceBlock:(FaceBlock)block; - (void)setImage:(UIImage *)image ImageText:(NSString *)text; @end
// FaceView.m
#import "FaceView.h"
@interface FaceView ()
@property (strong, nonatomic) FaceBlock block;
@property (strong, nonatomic) UIImageView *imageView;
@end
@implementation FaceView
// 初始化表情
- (id)initWithFrame:(CGRect)frame {
// 固定 30x30
frame.size.height = 30;
frame.size.width = 30;
self = [super initWithFrame:frame];
if (self) {
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[self addSubview:self.imageView];
}
return self;
}
- (void)setFaceBlock:(FaceBlock)block {
self.block = block;
}
- (void)setImage:(UIImage *)image ImageText:(NSString *)text {
[self.imageView setImage:image];
self.headerImage = image;
self.imageText = text;
}
// 點擊時回調
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
// 判斷觸摸結束點是否還在圖片範圍內
if (CGRectContainsPoint(self.bounds, point)) {
self.block(self.headerImage, self.imageText);
}
}
@end
本質上就是一個自帶回調的自訂按鈕。
它組合了 FaceView 與 UIScrollView,並用自動佈局配置底部按鈕。
// FunctionView.h #import <UIKit/UIKit.h> // 定義對應的 block 類型,用於資料回傳 typedef void (^FunctionBlock)(UIImage *image, NSString *imageText); @interface FunctionView : UIView @property (nonatomic, strong) NSString *plistFileName; // 資源檔名 - (void)setFunctionBlock:(FunctionBlock)block; @end
常用表情取自資料庫,全部表情則讀 plist:
// FunctionView.m
#import "FunctionView.h"
#import "FaceView.h"
#import "ImageModelClass.h"
#import "HistoryImage.h"
@interface FunctionView ()
@property (strong, nonatomic) FunctionBlock block;
@property (strong, nonatomic) UIImage *headerImage; // 暫存回調用的表情
@property (strong, nonatomic) NSString *imageText; // 暫存回調用的文字
@property (strong, nonatomic) UIScrollView *headerScrollView;
@property (strong, nonatomic) ImageModelClass *imageModel; // 資料模型
@end
@implementation FunctionView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.imageModel = [[ImageModelClass alloc] init];
// 全部表情按鈕
UIButton *faceButton = [[UIButton alloc] initWithFrame:CGRectZero];
faceButton.backgroundColor = [UIColor grayColor];
[faceButton setTitle:@"全部表情" forState:UIControlStateNormal];
[faceButton setShowsTouchWhenHighlighted:YES];
[faceButton addTarget:self action:@selector(tapButton1:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:faceButton];
// 常用表情按鈕
UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectZero];
moreButton.backgroundColor = [UIColor orangeColor];
[moreButton setTitle:@"常用表情" forState:UIControlStateNormal];
[moreButton setShowsTouchWhenHighlighted:YES];
[moreButton addTarget:self action:@selector(tapButton2:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:moreButton];
// 開啟自動佈局
faceButton.translatesAutoresizingMaskIntoConstraints = NO;
moreButton.translatesAutoresizingMaskIntoConstraints = NO;
// 水平約束:兩顆按鈕平分寬度
NSArray *buttonH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[faceButton][moreButton(==faceButton)]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(faceButton, moreButton)];
[self addConstraints:buttonH];
// 垂直約束:固定高度 44 並貼齊底部
NSArray *button1V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[faceButton(44)]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(faceButton)];
[self addConstraints:button1V];
NSArray *button2V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[moreButton(44)]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(moreButton)];
[self addConstraints:button2V];
[self tapButton1:nil]; // 預設顯示全部表情
}
return self;
}
- (void)setFunctionBlock:(FunctionBlock)block {
self.block = block;
}
// 點擊「全部表情」:從 plist 載入
- (void)tapButton1:(id)sender {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:self.plistFileName ofType:@"plist"];
NSArray *headers = [NSArray arrayWithContentsOfFile:path];
if (headers.count == 0) {
NSLog(@"訪問的 plist 檔案不存在");
} else {
[self header:headers];
}
}
// 點擊「常用表情」:從資料庫撈
- (void)tapButton2:(id)sender {
NSArray *imageData = [self.imageModel queryAll];
NSMutableArray *headers = [NSMutableArray arrayWithCapacity:imageData.count];
HistoryImage *tempData;
for (int i = 0; i < imageData.count; i++) {
tempData = imageData[i];
// 轉換成 header: 方法要吃的格式
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
[dic setObject:tempData.imageText forKey:@"chs"];
UIImage *image = [UIImage imageWithData:tempData.headerImage];
[dic setObject:image forKey:@"png"];
[headers addObject:dic];
}
[self header:headers];
}
// 把表情鋪到 scrollView 上
- (void)header:(NSArray *)headers {
[self.headerScrollView removeFromSuperview];
self.headerScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
[self addSubview:self.headerScrollView];
self.headerScrollView.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *scrollH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_headerScrollView]-10-|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(_headerScrollView)];
[self addConstraints:scrollH];
NSArray *scrolV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_headerScrollView]-50-|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(_headerScrollView)];
[self addConstraints:scrolV];
CGFloat scrollHeight = (self.frame).size.height - 60;
// 依表情數量算出 contentSize 寬度
CGFloat width = (headers.count / (scrollHeight / 30)) * 30;
self.headerScrollView.contentSize = CGSizeMake(width, scrollHeight);
self.headerScrollView.pagingEnabled = YES;
CGFloat x = 0;
CGFloat y = 0;
for (int i = 0; i < headers.count; i++) {
UIImage *image;
if ([headers[i][@"png"] isKindOfClass:[NSString class]]) {
image = [UIImage imageNamed:headers[i][@"png"]];
} else {
image = headers[i][@"png"];
}
NSString *imageText = headers[i][@"chs"];
y = (i % (int)(scrollHeight / 30)) * 30;
x = (i / (int)(scrollHeight / 30)) * 30;
FaceView *face = [[FaceView alloc] initWithFrame:CGRectMake(x, y, 0, 0)];
[face setImage:image ImageText:imageText];
// 用 weak 避免 block 造成循環引用
__weak __block FunctionView *copy_self = self;
[face setFaceBlock:^(UIImage *image, NSString *imageText) {
copy_self.block(image, imageText);
};
[self.headerScrollView addSubview:face];
}
[self.headerScrollView setNeedsDisplay];
}
@end
三個重點:遍歷資源或資料庫結果鋪進 ScrollView;為元件加上約束以適配不同螢幕;用 __weak __block 打斷 block 與 self 之間的循環引用。
就是鍵盤上方那條類似 TabBar 的東西,鍵盤彈出時它會跟著移到鍵盤之上。
// ToolView.h #import <UIKit/UIKit.h> // 定義 block 類型,把被點擊按鈕的 index 回傳到 Controller typedef void (^ToolIndex)(NSInteger index); @interface ToolView : UIView - (void)setToolIndex:(ToolIndex)toolBlock; @end
// ToolView.m
#import "ToolView.h"
@interface ToolView ()
@property (nonatomic, strong) ToolIndex myBlock;
@end
@implementation ToolView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 表情按鈕
UIButton *faceButton = [[UIButton alloc] initWithFrame:CGRectZero];
faceButton.backgroundColor = [UIColor orangeColor];
[faceButton setTitle:@"表情" forState:UIControlStateNormal];
[faceButton setShowsTouchWhenHighlighted:YES];
[faceButton addTarget:self action:@selector(tapFaceButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:faceButton];
// 更多按鈕
UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectZero];
moreButton.backgroundColor = [UIColor grayColor];
[moreButton setTitle:@"More" forState:UIControlStateNormal];
[moreButton setShowsTouchWhenHighlighted:YES];
[moreButton addTarget:self action:@selector(tapMoreButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:moreButton];
// 用約束讓兩顆按鈕填滿整個 ToolView
faceButton.translatesAutoresizingMaskIntoConstraints = NO;
moreButton.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *buttonH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[faceButton][moreButton(==faceButton)]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(faceButton, moreButton)];
[self addConstraints:buttonH];
NSArray *button1V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[faceButton]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(faceButton)];
[self addConstraints:button1V];
NSArray *button2V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[moreButton]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(moreButton)];
[self addConstraints:button2V];
}
return self;
}
- (void)setToolIndex:(ToolIndex)toolBlock {
self.myBlock = toolBlock;
}
- (void)tapFaceButton:(id)sender {
self.myBlock(1);
}
- (void)tapMoreButton:(id)sender {
self.myBlock(2);
}
@end
MoreView 的封裝方式與上面類似,這裡不重複貼。運行效果:

資料模型很單純,time 用來記錄使用時間以支援排序:

// ImageModelClass.h #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "HistoryImage.h" @interface ImageModelClass : NSObject - (void)save:(NSData *)image ImageText:(NSString *)imageText; // 儲存 - (NSArray *)queryAll; // 查詢全部 @end
// ImageModelClass.m
#import "ImageModelClass.h"
@interface ImageModelClass ()
@property (nonatomic, strong) NSManagedObjectContext *manager;
@end
@implementation ImageModelClass
- (instancetype)init {
self = [super init];
if (self) {
// 透過 AppDelegate 取得 context
UIApplication *application = [UIApplication sharedApplication];
id delegate = application.delegate;
self.manager = [delegate managedObjectContext];
}
return self;
}
- (void)save:(NSData *)image ImageText:(NSString *)imageText {
if (image != nil) {
NSArray *result = [self search:imageText];
HistoryImage *myImage;
if (result.count == 0) {
// 沒記錄過就新增
myImage = [NSEntityDescription insertNewObjectForEntityForName:
NSStringFromClass([HistoryImage class])
inManagedObjectContext:self.manager];
myImage.imageText = imageText;
myImage.headerImage = image;
myImage.time = [NSDate date];
} else {
// 有記錄就只更新時間,把它頂到最前面
myImage = result[0];
myImage.time = [NSDate date];
}
NSError *error = nil;
if (![self.manager save:&error]) {
NSLog(@"保存出錯 %@", [error localizedDescription]);
}
}
}
// 依文字查找
- (NSArray *)search:(NSString *)image {
NSArray *result;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
initWithEntityName:NSStringFromClass([HistoryImage class])];
// 加謂詞條件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"imageText=%@", image];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
result = [self.manager executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"查詢錯誤:%@", [error localizedDescription]);
}
return result;
}
// 查詢全部,按時間倒序
- (NSArray *)queryAll {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
initWithEntityName:NSStringFromClass([HistoryImage class])];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:NO];
[fetchRequest setSortDescriptors:@[sortDescriptor]];
NSError *error = nil;
NSArray *result = [self.manager executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"查詢錯誤:%@", [error localizedDescription]);
}
return result;
}
@end
儲存時先查一次是否存在,存在就更新時間、不存在才插入——這讓「常用表情」天然變成一個以最近使用時間排序的清單,寫到這裡還真有點像在用 Hibernate。
@interface MainViewController () // 自訂元件 @property (nonatomic, strong) ToolView *toolView; @property (nonatomic, strong) FunctionView *functionView; @property (nonatomic, strong) MoreView *moreView; // 系統元件 @property (strong, nonatomic) IBOutlet UITextView *myTextView; @property (strong, nonatomic) NSDictionary *keyBoardDic; @property (strong, nonatomic) IBOutlet UIImageView *imageView; // 資料層 @property (strong, nonatomic) ImageModelClass *imageMode; @end
- (void)viewDidLoad {
[super viewDidLoad];
self.imageMode = [[ImageModelClass alloc] init];
// 表情面板
self.functionView = [[FunctionView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
self.functionView.backgroundColor = [UIColor blackColor];
self.functionView.plistFileName = @"emoticons";
__weak __block MainViewController *copy_self = self;
[self.functionView setFunctionBlock:^(UIImage *image, NSString *imageText) {
NSString *str = [NSString stringWithFormat:@"%@%@", copy_self.myTextView.text, imageText];
copy_self.myTextView.text = str;
copy_self.imageView.image = image;
// 把用過的表情存起來
NSData *imageData = UIImagePNGRepresentation(image);
[copy_self.imageMode save:imageData ImageText:imageText];
}];
// 擴充面板
self.moreView = [[MoreView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
self.moreView.backgroundColor = [UIColor blackColor];
[self.moreView setMoreBlock:^(NSInteger index) {
NSLog(@"MoreIndex = %d", index);
}];
// 工具列
self.toolView = [[ToolView alloc] initWithFrame:CGRectZero];
self.toolView.backgroundColor = [UIColor blackColor];
[self.view addSubview:self.toolView];
self.toolView.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *toolHConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_toolView]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(_toolView)];
[self.view addConstraints:toolHConstraint];
NSArray *toolVConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[_toolView(44)]|"
options:0 metrics:0 views:NSDictionaryOfVariableBindings(_toolView)];
[self.view addConstraints:toolVConstraint];
// 工具列回調
[self.toolView setToolIndex:^(NSInteger index) {
switch (index) {
case 1: [copy_self changeKeyboardToFunction]; break;
case 2: [copy_self changeKeyboardToMore]; break;
default: break;
}
}];
// 監聽鍵盤,用來推動工具列位置
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyNotification:)
name:UIKeyboardWillChangeFrameNotification object:nil];
// 給 TextView 加一個「完成」工具列
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
UIBarButtonSystemItemDone target:self action:@selector(tapDone:)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
toolBar.items = @[item2, item1, item3];
self.myTextView.inputAccessoryView = toolBar;
}
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration {
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
CGRect frame = self.functionView.frame;
frame.size.height = 216;
self.functionView.frame = frame;
self.moreView.frame = frame;
}
if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
CGRect frame = self.functionView.frame;
frame.size.height = 150;
self.functionView.frame = frame;
self.moreView.frame = frame;
}
}
橫屏時鍵盤的座標系與我們的 frame 座標系不同,必須先做轉換:
- (void)keyNotification:(NSNotification *)notification {
self.keyBoardDic = notification.userInfo;
// 鍵盤移動後的座標
CGRect rect = [self.keyBoardDic[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 轉成當前 window 的座標系
CGRect r1 = [self.view convertRect:rect fromView:self.view.window];
[UIView animateWithDuration:[self.keyBoardDic[UIKeyboardAnimationDurationUserInfoKey] floatValue]
animations:^{
[UIView setAnimationCurve:[self.keyBoardDic[UIKeyboardAnimationCurveUserInfoKey] doubleValue]];
CGRect frame = self.toolView.frame;
frame.origin.y = r1.origin.y - frame.size.height;
self.toolView.frame = frame;
}];
}
- (void)changeKeyboardToFunction {
if ([self.myTextView.inputView isEqual:self.functionView]) {
self.myTextView.inputView = nil;
[self.myTextView reloadInputViews];
} else {
self.myTextView.inputView = self.functionView;
[self.myTextView reloadInputViews];
}
if (![self.myTextView isFirstResponder]) {
[self.myTextView becomeFirstResponder];
}
}
整個實作的難點不在表情本身,而在螢幕適配——尤其橫屏時鍵盤座標系與自身 frame 座標系不一致,必須轉換。另外提醒兩點現代實務上的調整:一是自訂鍵盤若要給其他 App 使用,需要另外建立 Keyboard Extension target 並遵守 App Group 共用規則,這套寫法比較偏向「App 內自用的輸入元件」;二是 scheduleNotification 系列舊 API 與 NSLayoutConstraint 手寫約束都仍可用,但新專案建議改用 UIStackView 與 keyboardLayoutGuide,能省下不少座標計算。