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

iOS 開發除錯:ScrollView 無法顯示內容的原因分析

編輯:iOS 開發綜合

本文記錄一個實作中的坑:建立了一個 scrollview,並在裡面加入 imageView,結果圖片卻怎麼樣都顯示不出來。

一、問題程式碼

ImagePageView 的定義如下:

@interface ImagePageView : UIView
@property (nonatomic,retain) UIImageView *imageViewOne;
@property (nonatomic,retain) UIImageView *imageViewTwo;
- (void)imageViewV:(int)pageNum;
- (void)imageViewH:(int)pageNum;
@end

@implementation ImagePageView
@synthesize imageViewOne = _imageViewOne;
@synthesize imageViewTwo = _imageViewTwo;

- (UIImageView *)imageViewOne
{
    if (!_imageViewOne) {
        _imageViewOne = [[UIImageView alloc] init];
        [self addSubview:_imageViewOne];
    }
    return _imageViewOne;
}

- (void)imageViewV:(int)pageNum
{
    _imageViewOne.image = [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[array objectAtIndex:pageNum] ofType:nil]] autorelease];
    _imageViewOne.frame = self.bounds;
}

二、問題與修正

問題就在於:直接使用底層的成員變數 _imageViewOne,並不會呼叫到自訂的 lazy 初始化方法(- (UIImageView *)imageViewOne),因此 _imageViewOne 一直是 nil,導致圖片無法顯示。

把程式碼改成透過 self.imageViewOne 存取即可:

- (void)imageViewV:(int)pageNum
{
    self.imageViewOne.image = [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[array objectAtIndex:pageNum] ofType:nil]] autorelease];
    self.imageViewOne.frame = self.bounds;
}

因為 self.imageViewOne 會觸發 getter 方法,走進 lazy 初始化的邏輯,imageView 才會被正確建立並加入視圖。這也是為什麼「用 _ 開頭的成員變數」與「用 self. 存取屬性」在 Objective-C 中有著關鍵差異。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved