您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

純程式碼打造高仿《內涵段子》:兩週業餘時間的完整開發日誌

編輯:iOS 開發基礎

Github 地址:https://github.com/Charlesyaoxin/NeiHanDuanZI

專案緣起

花了大約兩週的業餘時間,模仿了頭條旗下的 iOS 端 App《內涵段子》(8.30 – 9.11)。如果你也覺得有意思,歡迎給個 star。

專案以 Objective-C 撰寫。如果你把碼下載下來翻一翻,會發現整個專案沒有一個 storyboard 或 nib。這不是因為不愛用,而是因為一直想試著用純程式碼完成一個專案。想法要落地,光想不做是不行的,於是就開始了我的「內涵之旅」。

開發日誌

8.30 主要是搭架構:建立 UITabbarController + UINavigationController 的骨架,並把常用工具類與巨集定義拉進來。

// 添加子控制器
- (void)addChildViewControllerWithClassname:(NSString *)classname
                                  imagename:(NSString *)imagename
                                      title:(NSString *)title {
    UIViewController *vc = [[NSClassFromString(classname) alloc] init];
    NHBaseNavigationViewController *nav =
        [[NHBaseNavigationViewController alloc] initWithRootViewController:vc];

    nav.tabBarItem.title  = title;
    nav.tabBarItem.image  = [UIImage imageNamed:imagename];
    nav.tabBarItem.selectedImage =
        [[UIImage imageNamed:[imagename stringByAppendingString:@"_press"]]
         imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    [self addChildViewController:nav];
}

8.31 開始往昨天搭好的類別裡填內容,先啃最複雜的首頁。參考頭條首頁的架構來做,接著抓介面、加入公共請求參數、完善請求基類。同時穿插幾個較簡單的列表頁,由淺入深有助於在開發過程中累積自信心。

/** 鏈接 */
@property (nonatomic, copy) NSString *nh_url;
/** 預設 GET */
@property (nonatomic, assign) BOOL nh_isPost;
/** 圖片數組 */
@property (nonatomic, strong) NSArray *nh_imageArray;

/** 構造方法 */
+ (instancetype)nh_request;
+ (instancetype)nh_requestWithUrl:(NSString *)nh_url;
+ (instancetype)nh_requestWithUrl:(NSString *)nh_url isPost:(BOOL)nh_isPost;
+ (instancetype)nh_requestWithUrl:(NSString *)nh_url
                           isPost:(BOOL)nh_isPost
                         delegate:(id)nh_delegate;

/** 開始請求(設了代理就不需要 block 回調) */
- (void)nh_sendRequest;

/** 開始請求,block 回調優先級高於代理 */
- (void)nh_sendRequestWithCompletion:(NHAPIDicCompletion)completion;

9.1 完成控制器、cell 以及純文字/圖片資料的展示,並封裝發布頁的檢視。

9.2 – 9.4 首頁回調處理與發現頁。

typedef NS_ENUM(NSUInteger, NHHomeTableViewCellItemType) {
    /** 點贊 */
    NHHomeTableViewCellItemTypeLike = 1,
    /** 踩 */
    NHHomeTableViewCellItemTypeDontLike,
    /** 評論 */
    NHHomeTableViewCellItemTypeComment,
    /** 分享 */
    NHHomeTableViewCellItemTypeShare
};

@protocol NHHomeTableViewCellDelegate

/** 點擊瀏覽大圖 */
- (void)homeTableViewCell:(NHHomeTableViewCell *)cell
         didClickImageView:(UIImageView *)imageView
             currentIndex:(NSInteger)currentIndex
                      urls:(NSArray *)urls;

/** 播放影片 */
- (void)homeTableViewCell:(NHHomeTableViewCell *)cell
  didClickVideoWithVideoUrl:(NSString *)videoUrl
                videoCover:(NHBaseImageView *)baseImageView;

/** 分類 */
- (void)homeTableViewCellDidClickCategory:(NHHomeTableViewCell *)cell;

/** 個人中心 */
- (void)homeTableViewCell:(NHHomeTableViewCell *)cell
gotoPersonalCenterWithUserInfo:(NHNeiHanUserInfoModel *)userInfoModel;

/** 點擊底部 item */
- (void)homeTableViewCell:(NHHomeTableViewCell *)cell
        didClickItemWithType:(NHHomeTableViewCellItemType)itemType;

@optional
/** 點擊關注 */
- (void)homeTableViewCellDidClickAttention:(NHHomeTableViewCell *)cell;
/** 刪除 */
- (void)homeTableViewCellDidClickClose:(NHHomeTableViewCell *)cell;

@end

@interface NHHomeTableViewCell : NHBaseTableViewCell

@property (nonatomic, weak)   id  delegate;
@property (nonatomic, strong) NHHomeTableViewCellFrame *cellFrame;
@property (nonatomic, strong) NHDiscoverSearchCommonCellFrame *searchCellFrame;
/** 用來判斷是否顯示刪除按鈕 */
@property (nonatomic, assign) BOOL isFromHomeController;

- (void)setCellFrame:(NHHomeTableViewCellFrame *)cellFrame isDetail:(BOOL)isDetail;
- (void)setSearchCellFrame:(NHDiscoverSearchCommonCellFrame *)searchCellFrame
                   keyWord:(NSString *)keyWord;
- (void)didDigg;
- (void)didBury;

@end

9.5 – 9.7 審核頁的邏輯與動畫,發現頁的輪播圖與自訂 pageControl。

- (void)setCurrentIndex:(NSInteger)currentIndex {
    _currentIndex = currentIndex;

    UIBezierPath *path = [UIBezierPath bezierPath];
    CGFloat delta = self.width
                  - self.numberOfItems * self.pageWidth
                  + (self.numberOfItems - 1) * self.pageSpace - 15;

    [path moveToPoint:CGPointMake(currentIndex * self.pageWidth
                                + currentIndex * self.pageSpace + delta, 5)];
    [path addLineToPoint:CGPointMake((currentIndex + 1) * self.pageWidth
                                   + currentIndex * self.pageSpace + delta, 5)];

    CGFloat duration = 1.0;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration = duration;
    animation.fromValue = (__bridge id _Nullable)(self.prePath.CGPath);
    animation.toValue   = (__bridge id _Nullable)(path.CGPath);

    [self.selectedLayer addAnimation:animation forKey:@""];
    self.prePath = path;
}

9.8 – 9.9 搜尋頁邏輯、個人中心內容填充、部分空資料頁的檢視。

9.10 影片播放與各處修補。

9.11 補完部分動畫(點贊、踩、關注等),簡單測試,晚上寫文章並上傳 Github。

@interface NHCustomCommonEmptyView : UIView

@property (nonatomic, weak) UIImageView *topTipImageView;
@property (nonatomic, weak) UILabel *firstL;
@property (nonatomic, weak) UILabel *secondL;

- (instancetype)initWithTitle:(NSString *)title
                  secondTitle:(NSString *)secondTitle
                     iconname:(NSString *)iconname;

- (instancetype)initWithAttributedTitle:(NSMutableAttributedString *)attributedTitle
                   secondAttributedTitle:(NSMutableAttributedString *)secondAttributedTitle
                                iconname:(NSString *)iconname;

- (void)showInView:(UIView *)view;

@end

主要功能

首頁

點贊、踩、分享、收藏、複製鏈接、影片播放、上下拉刷新、評論列表、關注列表。

要點:把請求到的列表資料轉成模型陣列,再預先算出每個模型對應的 frame 陣列。這樣做的好處是避免 cellForRow 與高度計算重複執行;代價是計算量大,需要耐心調。

利用檢視的 drawRect 達到滾動時的視差穿透效果;封裝分享檢視(NHHomeShareView);封裝帶高斯模糊的自訂彈窗,效果與系統 UIAlertView 相近但更好。

評論列表:用 YYLabel 搭配 NSAttributedString,把 @ 到的使用者名稱高亮並掛上點擊事件。

分享:封裝分享管理類,集中配置友盟 appKey、URLScheme 等必要設定。

圖片瀏覽器:依資料排版九宮格,並把網路圖片的請求邏輯全部收攏到自訂的 NHBaseImageView 中。

GIF 處理:封裝一個繼承自 UIImageView 的 GIF 檢視,頂部加上 loading。

發現

輪播、熱吧列表、推薦關注、訂閱列表、搜尋、附近的人與篩選。

要點:用 UICollectionView 實作無限循環輪播,並用貝茲曲線自訂 pageControl;切換索引時曲線以 layer 動畫平滑位移。

附近的人:App 啟動時先請求一次定位並保存經緯度,進入該頁時重新定位以取得最新座標,再拉取列表;篩選檢視支援依性別過濾。

搜尋:自訂搜尋框(業務邏輯太深的時候,系統的 UISearchBar 會不夠用)。關鍵字結果轉為富文本,搭配多種 cell 呈現。

這裡有個關鍵點:搜尋需要同時並發呼叫三個介面(使用者、動態、熱吧),因此用到了 dispatch_group 來聚合多個非同步請求。如果專案使用 RAC,就可以不用 dispatch_group 了。

審核

舉報、喜歡/不喜歡、手動左滑查看新內容,並以貝茲曲線搭配 CAShapeLayer 製作載入動畫。

要點:用 UICollectionView 做分頁展示並自訂 UICollectionViewFlowLayout;封裝舉報底部檢視;封裝帶進度條的 loading 檢視(NHCheckTableViewProgressBar),進度條以 CAShapeLayer + 貝茲曲線 + 基本動畫實作。

這裡用 UIWebView 載入 GIF 的做法其實不算理想,日後可替換。

發布

選擇熱吧、發布圖文。

要點:版面用 Masonry 佈局,並監聽鍵盤彈出/收起的通知來更新約束;圖片選擇完成後的畫面用 UICollectionView 排版;textView 自行實作了佔位文字與高度自適應。

個人中心

使用者資訊寫死在本機,模擬登入邏輯。

用歸檔(NSKeyedArchiver)把使用者資訊存在本機,再用 NSUserDefaults 記錄登入狀態;修改頭像時彈出自訂的 ActionSheet(NHCustomActionSheet)。

專案中的工具類與管理類數量可觀,有興趣歡迎直接去看原始碼,另外還有幾個堪用的小 Demo 也一併開源了。

程式碼節選

請求基類:

@protocol NHBaseRequestReponseDelegate
@required
- (void)requestSuccessReponse:(BOOL)success
                     response:(id)response
                      message:(NSString *)message;
@end

typedef void (^NHAPIDicCompletion)(id response, BOOL success, NSString *message);

@interface NHBaseRequest : NSObject
@property (nonatomic, weak)   id  nh_delegate;
@property (nonatomic, copy)   NSString *nh_url;
@property (nonatomic, assign) BOOL nh_isPost;
@property (nonatomic, strong) NSArray *nh_imageArray;
@end

審核頁的進度條動畫,用貝茲曲線做形變:

- (void)setLeftScale:(CGFloat)leftScale {
    _leftScale = leftScale;

    NSInteger leftDelta = leftScale * 100;
    self.leftL.text = [NSString stringWithFormat:@"%ld%%", leftDelta];

    CGFloat height = 10;
    UIRectCorner corner = (leftScale == 1.0)
                        ? UIRectCornerAllCorners
                        : (UIRectCornerTopLeft | UIRectCornerBottomLeft);

    UIBezierPath *bezierPath0 =
        [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, self.height / 2.0 - height / 2.0, 0, height)
                              byRoundingCorners:corner
                                    cornerRadii:CGSizeMake(5.f, 5.f)];

    UIBezierPath *bezierPath1 =
        [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, self.height / 2.0 - height / 2.0,
                                                          self.width * self.leftScale, height)
                              byRoundingCorners:corner
                                    cornerRadii:CGSizeMake(5.f, 5.f)];

    CGFloat duration = 0.8;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration = duration;
    animation.fromValue = (__bridge id _Nullable)(bezierPath0.CGPath);
    animation.toValue   = (__bridge id _Nullable)(bezierPath1.CGPath);

    [self.leftLayer addAnimation:animation forKey:@""];
}

首頁的滾動穿透效果:

- (void)setProgress:(CGFloat)progress {
    _progress = progress;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [_fillColor set];

    CGRect newRect = rect;
    newRect.size.width = rect.size.width * self.progress;
    UIRectFillUsingBlendMode(newRect, kCGBlendModeSourceIn);
}

專案裡還有自訂的 ActionSheet、AlertView、SegmentControl、pageControl,以及這套封裝的 TableView 類(支援註冊 cell/headerFooter、單行與多行刷新、刪除並可自訂動畫),有興趣可直接查閱原始碼。

回顧與總結

  • 整個專案做得比較趕,前後不到兩週。
  • 再強調一次:這是純程式碼實作,並不是不習慣用 nib 或 storyboard,而是想還一個長年心願。
  • 所有內容都是公司的事忙完之後寫的,晚上回家也投入了不少時間。
  • 部分類別與檔案是先前整理過的成果,直接搬過來用,確實省下不少時間。
  • Bug 還有不少,沒怎麼細測就推上 Github 了,之後應該會持續更新。
  • 下一階段方向大概是 Swift,目前手上有一個完成度約 75% 的小專案,未來也會開源。
  • 歡迎提供建議,一起進步。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved