本文以一個完整的音樂播放器專案為例,把「列表展示 → 數據建模 → 界面美化 → Cell 封裝 → 頁面切換」這條主線走完。適合已經掌握 Objective-C 基礎語法、想要把知識串成一個完整 App 的初學者跟著做一遍。
動手寫程式碼之前,先把圖片、plist 數據等資源按目錄分類放好。結構清晰的專案後續維護成本會低很多。

新建一個繼承自 UITableViewController 的控制器,負責展示歌曲清單。

再新建一個繼承自 UIViewController 的控制器,作為播放界面使用。

刪除專案自帶的預設控制器,改為拖入一個導航控制器(UINavigationController),並把其中的 tableView 控制器的 Custom Class 指向剛才建立的列表控制器類。

plist 中每一條記錄對應一首歌,我們為它建立一個模型類 YYMusicModel,屬性與 plist 中的鍵一一對應。

YYMusicModel.h:
// // YYMusicModel.h // 20-音頻處理(音樂播放器1) // #import <Foundation/Foundation.h> @interface YYMusicModel : NSObject /** 歌曲名字 */ @property (copy, nonatomic) NSString *name; /** 歌曲大圖 */ @property (copy, nonatomic) NSString *icon; /** 歌曲的文件名 */ @property (copy, nonatomic) NSString *filename; /** 歌詞的文件名 */ @property (copy, nonatomic) NSString *lrcname; /** 歌手 */ @property (copy, nonatomic) NSString *singer; /** 歌手圖標 */ @property (copy, nonatomic) NSString *singerIcon; @end
引入 MJExtension 這類字典轉模型的第三方框架,一行程式碼就能把整個 plist 陣列轉成模型陣列,省下大量重複的賦值工作。


此時列表已經能把歌名與歌手正常顯示出來:

圓形頭像是音樂類 App 的常見視覺語言。與其到處寫裁剪程式碼,不如封裝成 UIImage 的分類,一次實作到處都能呼叫。
UIImage+YY.h:
#import <UIKit/UIKit.h> @interface UIImage (YY) + (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor; @end
UIImage+YY.m:
#import "UIImage+YY.h"
@implementation UIImage (YY)
+ (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
// 1.加載原圖
UIImage *oldImage = [UIImage imageNamed:name];
// 2.開啟上下文(邊框會額外佔據 borderWidth 的寬度)
CGFloat imageW = oldImage.size.width + 2 * borderWidth;
CGFloat imageH = oldImage.size.height + 2 * borderWidth;
CGSize imageSize = CGSizeMake(imageW, imageH);
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
// 3.取得當前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 4.畫邊框(大圓)
[borderColor set];
CGFloat bigRadius = imageW * 0.5; // 大圓半徑
CGFloat centerX = bigRadius; // 圓心
CGFloat centerY = bigRadius;
CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ctx); // 畫圓
// 5.小圓,並進行裁剪(後續繪製才會受裁剪影響)
CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
CGContextClip(ctx);
// 6.畫圖
[oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
// 7.取圖
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 8.結束上下文
UIGraphicsEndImageContext();
return newImage;
}
@end
分類的使用方式:

完成後的效果:


推薦使用 Colours 這類框架,內建大量現成的色值(例如 skyBlueColor),能避免專案裡散落一堆硬編碼的色值。

YYMusicsViewController.m:
#import "YYMusicsViewController.h"
#import "YYMusicModel.h"
#import "MJExtension.h"
#import "UIImage+YY.h"
#import "Colours.h"
@interface YYMusicsViewController ()
@property (nonatomic, strong) NSArray *musics;
@end
@implementation YYMusicsViewController
#pragma mark - 懶加載
- (NSArray *)musics
{
if (_musics == nil) {
_musics = [YYMusicModel objectArrayWithFilename:@"Musics.plist"];
}
return _musics;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
#pragma mark - Table view data source
/** 一共多少組 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
/** 每組多少行 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.musics.count;
}
/** 每組每行的 cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"ID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
// 取出數據模型
YYMusicModel *model = self.musics[indexPath.row];
cell.textLabel.text = model.name;
cell.detailTextLabel.text = model.singer;
cell.imageView.image = [UIImage circleImageWithName:model.singerIcon
borderWidth:1
borderColor:[UIColor skyBlueColor]];
return cell;
}
/** 設置每個 cell 的高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;
}
/** cell 的點擊事件 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 取消選中被點擊的這一行
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
把 cell 的取用與賦值邏輯寫在控制器裡,會讓 cellForRowAtIndexPath: 越來越臃肿。更好的做法是新建一個 YYMusicCell 類,繼承自 UITableViewCell,對外只暴露一個模型屬性,內部自己完成視圖更新。
YYMusicCell.h:
#import <UIKit/UIKit.h> @class YYMusicModel; @interface YYMusicCell : UITableViewCell + (instancetype)cellWithTableView:(UITableView *)tableView; @property (nonatomic, strong) YYMusicModel *music; @end
YYMusicCell.m:
#import "YYMusicCell.h"
#import "YYMusicModel.h"
#import "Colours.h"
#import "UIImage+YY.h"
@implementation YYMusicCell
// 返回一個 cell
+ (instancetype)cellWithTableView:(UITableView *)tableView
{
static NSString *ID = @"ID";
YYMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[YYMusicCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
return cell;
}
- (void)setMusic:(YYMusicModel *)music
{
_music = music;
self.textLabel.text = music.name;
self.detailTextLabel.text = music.singer;
self.imageView.image = [UIImage circleImageWithName:music.singerIcon
borderWidth:1
borderColor:[UIColor skyBlueColor]];
}
@end
封裝之後,控制器裡的 cellForRowAtIndexPath: 只剩下三行,可讀性明顯提升:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
YYMusicCell *cell = [YYMusicCell cellWithTableView:tableView];
cell.music = self.musics[indexPath.row];
return cell;
}

[tableView deselectRowAtIndexPath:indexPath animated:YES];,否則返回列表時該行仍處於高亮狀態。(1)模態跳轉(modal),分手動 performSegue 與自動 segue 兩種;
(2)使用 xib 建立播放界面。
先在 storyboard 中拖入一個控制器,把它的 Custom Class 關聯到播放控制器類。

接著按住 Control 從 cell 拖線到目標控制器,建立手動跳轉。

然後為這條 segue 設定 Identifier。

最後在 cell 的點擊事件中觸發跳轉。

不推薦模態方案的原因:選中歌曲跳轉到播放界面後,若要回到列表,最直覺的做法是在播放控制器上放一個返回按鈕,點擊時把當前控制器 dismiss 掉。問題就在這裡——控制器一旦被銷毀,正在播放的音樂也隨之停止。加上播放界面的布局是固定不變的,每次都以堆疊方式重建並沒有必要。
為播放控制器新建對應的 xib,界面結構如下:

由於播放控制器只需建立一次,建議用懶加載持有它(也可以把播放器設計成單例):
#import "YYMusicsViewController.h"
#import "YYMusicModel.h"
#import "MJExtension.h"
#import "YYMusicCell.h"
#import "YYPlayingViewController.h"
@interface YYMusicsViewController ()
@property (nonatomic, strong) NSArray *musics;
@property (nonatomic, strong) YYPlayingViewController *playingViewController;
@end
@implementation YYMusicsViewController
#pragma mark - 懶加載
- (NSArray *)musics
{
if (_musics == nil) {
_musics = [YYMusicModel objectArrayWithFilename:@"Musics.plist"];
}
return _musics;
}
- (YYPlayingViewController *)playingViewController
{
if (_playingViewController == nil) {
_playingViewController = [[YYPlayingViewController alloc] init];
}
return _playingViewController;
}
(1)利用 Auto Layout 添加約束,同時適配不同尺寸與系統版本的螢幕。
(2)歌名與歌手所在的容器視圖需要設為半透明,透明度設為 30% 左右視覺效果較好。


注意:不要在 storyboard 的屬性面板上直接調透明度。這樣做會連子控制項一起變透明。正確做法是新建一個 UIView 作為容器,只調容器的透明度,或者改為在程式碼中設定背景色為半透明色。

(3)按鈕點擊時的高亮發光效果。

(4)播放界面收起後把 view 設為 hidden,可以節省一部分渲染開銷。
(5)在控制器切換的動畫過程中,把整個 window 的 userInteractionEnabled 設為 NO,避免使用者連續快速點擊造成界面錯亂。
專案裡另外拖入了一個 UIView 的分類,用來簡化 frame 相關計算(例如 self.view.height、self.view.y 這類點語法),讓動畫程式碼更乾淨。
YYPlayingViewController.h:
#import <UIKit/UIKit.h> @interface YYPlayingViewController : UIViewController // 顯示控制器 - (void)show; @end
YYPlayingViewController.m:
#import "YYPlayingViewController.h"
@interface YYPlayingViewController ()
- (IBAction)exit;
@end
@implementation YYPlayingViewController
#pragma mark - 公共方法
- (void)show
{
// 1.禁用整個 app 的點擊事件
UIWindow *window = [UIApplication sharedApplication].keyWindow;
window.userInteractionEnabled = NO;
// 2.添加播放界面,view 大小覆蓋整個窗口
self.view.frame = window.bounds;
self.view.hidden = NO;
[window addSubview:self.view];
// 3.用動畫讓 view 從底部滑入
self.view.y = self.view.height;
[UIView animateWithDuration:0.25 animations:^{
self.view.y = 0;
} completion:^(BOOL finished) {
window.userInteractionEnabled = YES;
}];
}
#pragma mark - 內部的按鈕監聽方法
// 返回按鈕
- (IBAction)exit {
// 1.禁用整個 app 的點擊事件
UIWindow *window = [UIApplication sharedApplication].keyWindow;
window.userInteractionEnabled = NO;
// 2.動畫隱藏 view
[UIView animateWithDuration:0.25 animations:^{
self.view.y = window.height;
} completion:^(BOOL finished) {
window.userInteractionEnabled = YES;
// 隱藏 view 可以節省一些性能
self.view.hidden = YES;
}];
}
@end
列表控制器中 cell 的點擊事件只需一行呼叫:
/**
* cell 的點擊事件
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 取消選中被點擊的這一行
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// 調用公共方法顯示播放界面
[self.playingViewController show];
// 若改用模態跳轉,則替換為下面這行
// [self performSegueWithIdentifier:@"music2playing" sender:nil];
}
至此,歌曲列表、圓形頭像、Cell 封裝與播放界面的滑入動畫都已完成,下一篇再來處理真正的音頻播放邏輯。