2012-12-13 22 views
6

Tôi đã triển khai UICollectionView trong ứng dụng của mình. Vấn đề của tôi là tôi cần phải chọn (như nếu người dùng gõ vào nó) một ô programmatically. Phương pháp:Cách chọn mục/ô của UICollectionView từ mã

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
        animated:(BOOL)animated 
       scrollPosition:(UICollectionViewScrollPosition)scrollPosition 

Đó là một phần của lớp UICollectionView không phải là những gì tôi cần phải gọi, vì phương pháp này không gọi:

- (void)collectionView:(UICollectionView *)collectionView 
     didSelectItemAtIndexPath:(NSIndexPath *)indexPath 

Nó chỉ đặt selected tài sản của các tế bào để YES;

+2

Còn việc tự gọi phương thức sau khi bạn đã chọn ô của mình thì sao? Bạn có thể gọi [self collectionView: yourView didSelectItemAtIndexPath: yourIndexPath]; –

+0

Có. hiểu rồi. cảm ơn! –

+1

Có lẽ câu trả lời này sẽ giúp bạn http://stackoverflow.com/questions/13177201/select-items-programmatically-in-uicollectionview –

Trả lời

7

Tôi đang gọi [self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath] để chọn một ô theo chương trình. Nhưng trong ô phương thức luôn luôn là không. Điều này hoạt động hoàn hảo tốt khi người dùng chọn một ô.

+7

hoặc nhanh chóng, bạn có thể sử dụng: 'collectionView.delegate? .collectionView! (CollectionView, didSelectItemAtIndexPath: someIndexPath)' – mbuff24

+0

Điều đó hoạt động, thực tế là không nên gọi trực tiếp các phương thức ủy nhiệm (Khung nhìn Collection sẽ gọi phương thức đó đại biểu như Apple khuyến cáo). Như @leviathan đã đề cập "[selectItemAtIndexPath: animated: scrollPosition:]" sẽ không gọi phương thức ủy nhiệm để có cách tốt hơn để giải quyết vấn đề đó. – ppalancica

7

Trước tiên, bạn cần phải hiển thị ô đích, nếu không [yourCollectionView cellForItemAtIndexPath:yourIndexPath] sẽ luôn trả về 0.

// scroll to the cell 
[yourCollectionView scrollToItemAtIndexPath:yourIndexPath 
          atScrollPosition:UICollectionViewScrollPositionBottom 
            animated:NO]; 

// call delegate method 
[self collectionView:yourCollectionView didSelectItemAtIndexPath:yourIndexPath]; 

// now you have selected the cell and can do anything to it in the delegate method :-) 
+0

Ô của tôi luôn hiển thị, nhưng cellForItemAtIndexPath luôn trả về nil (ngay cả sau khi gọi scrollToItemAtIndexPath –

8

Vâng, đây là hành vi phù hợp. Tài liệu cho [selectItemAtIndexPath:animated:scrollPosition:]says:

Phương pháp này không gây ra bất kỳ phương pháp đại biểu lựa chọn có liên quan đến được gọi.