2012-10-17 20 views
71

Một UIViewController duy trì một tham chiếu đến một UICollectionView. Bộ điều khiển nên sửa đổi bố cục luồng tích hợp bằng cách sử dụng UICollectionViewDelegateFlowLayout.Cách đặt UICollectionViewDelegateFlowLayout?

Đó là khá dễ dàng để thiết lập của xem nguồn dữ liệu để tự:

MyViewController.m

- (void)viewDidLoad 
{ 
    self.collectionView.dataSource = self; 
} 

Nhưng làm cách nào để thiết lập bộ điều khiển được bố trí dòng chảy đại biểu về quan điểm?

- (void)viewDidLoad 
{ 
    self.collectionView.dataSource= self; 
    // self.collectionView.??? = self; 
} 

Tôi đã thử:

- (void)viewDidLoad 
{ 
    self.collectionView.dataSource= self; 
    self.collectionView.collectionViewLayout = self; 
} 

Nhưng tôi nhận được lỗi: "loại con trỏ không tương thích giao ...".

Bộ sưu tập file header trông như thế này:

MyViewController.h

@interface MyViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> 

Trả lời

182

Chỉ self.collectionView.delegate = self;. Lưu ý rằng UICollectionViewDelegateFlowLayout được kế thừa từ UICollectionViewDelegate.

Tôi thừa nhận nó có thể khiến bạn mất cảnh giác lúc đầu.

Ồ và điều này sẽ chỉ hoạt động nếu self.collectionView.collectionViewLayout thực sự được đặt thành bố cục luồng của bạn. (hoặc được đặt với initWithFrame:collectionViewLayout:)

+1

@JohnEstropia, xin lỗi, nhưng làm cách nào để init bố cục tùy chỉnh trong mã? Tôi thấy các ví dụ với bảng phân cảnh nhưng không phải với chính mã. Tôi nên làm gì? – gaussblurinc

+3

có thể, 'self.collectionViewLayout = UICollectionViewFlowLayout()', 'self.collectionViewLayout = [[UICollectionViewFlowLayout alloc] init]' –

7

Theo câu trả lời trước chỉ là ví dụ về sử dụng. Nó thực sự không rõ ràng nhưng tôi có thể cho thấy cách hoạt động:

@interface PrettyViewController()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource> 
    //some code 
@end 

@implementation PrettyViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.collectionView.delegate = self;//bingo! right here 
} 

#pragma mark - UICollectionViewDelegateFlowLayout 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section { 
    return CGSizeMake([[UIScreen mainScreen] bounds].size.width, 20.0); 
} 


@end 
Các vấn đề liên quan