1

나는 UICollectionView을 가지고 있으며 과 imagecollectionViewCell에 설정하려고합니다. 불행히도 나는 그 문제에 대해 어떤 레이블이나 다른 것을 얻는 것 같지 않습니다.맞춤형 UICollectionViewCell을 만드는 방법

여기 내 코드입니다 :

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

    UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)]; 
    if(indexPath.item %2 == 0){ 
     cell.backgroundColor=[UIColor blueColor]; 
     issue.text = @"Some Text"; 
     issue.textColor = [UIColor greenColor]; 
     issue.textAlignment = NSTextAlignmentCenter; 
    } 
    else { 
     cell.backgroundColor=[UIColor redColor]; 
     issue.text = @"Some Text"; 
     issue.textColor = [UIColor greenColor]; 
     issue.textAlignment = NSTextAlignmentCenter; 
    } 
} 

는 불행하게도 레이블이 표시되지되고 있으며 둘 다 레이블의 텍스트입니다.

업데이트 됨 :이 클래스 파일의 나머지 코드를 추가했습니다.

#import "ContainerListController.h" 
#import "ContainerController.h" 
#import "ContainerList.h" 


@implementation ContainerListController 


//Deallocate temp variables 
- (void)dealloc { 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

//Initiate objects 
- (id)init { 
    if (self = [super initWithTitle:LocStr(@"CONTAINER_LIST_TITLE") navBarHidden:NO]) { 
     m_paths = [ContainerList shared].paths; 

     [[NSNotificationCenter defaultCenter] addObserver:self 
      selector:@selector(onContainerListDidChange) 
      name:kSDKLauncherContainerListDidChange object:nil]; 
    } 

    return self; 
} 

//Load all the views. 
- (void)loadView { 
    //Allocate a UI view 
    self.view = [[UIView alloc] init]; 

    //Create flow layout 
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; 

    //Force Horizontal Scroll 
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; 
    layout.minimumInteritemSpacing =[[UIScreen mainScreen] bounds].size.width; 
    layout.minimumLineSpacing=0.0; 


    //Create Collection 
    UICollectionView *coll =[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout]; 

    //Allocations 
    m_coll = coll; 
    coll.dataSource =self; 
    coll.delegate =self; 
    coll.pagingEnabled = YES; 
    coll.collectionViewLayout = layout; 

    //Customize Cells 
    [coll registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [coll setBackgroundColor:[UIColor orangeColor]]; 

    [layout invalidateLayout]; 

    //Create the subview 
    [self.view addSubview:coll]; 




    //set minimum spacing 
    /*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){ 
     NSLog(@"Changed to landscape Spacing"); 
     layout.minimumLineSpacing = 100.0f; 
     layout.minimumInteritemSpacing = 100.0f; 
    } 
    else{ 

     layout.minimumLineSpacing = 40.0f; 
     layout.minimumInteritemSpacing = 40.0f; 
    }*/ 

    //Old Layout 
    //UITableView *table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain]; 
    //m_table = table; 
    //table.dataSource = self; 
    //table.delegate = self; 
    //[self.view addSubview:table]; 

} 

- (void)onContainerListDidChange { 
    m_paths = [ContainerList shared].paths; 
    [m_table reloadData]; 
    [m_coll reloadData]; 
} 

//Debugging components function 
/*-(void)printComps:(NSArray*) components{ 
    for (NSInteger i =0; i<16; i++) { 
     NSString * item; 
     item=components[i]; 
    } 
}*/ 

//old tableview cell 
- (UITableViewCell *) 
    tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
     reuseIdentifier:nil]; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    NSString *path = [m_paths objectAtIndex:indexPath.row]; 
    NSArray *components = path.pathComponents; 
    cell.textLabel.text = (components == nil || components.count == 0) ? 
     @"" : components.lastObject; 
    return cell; 
} 

//Old tableView 
- (void) 
    tableView:(UITableView *)tableView 
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    NSString *path = [m_paths objectAtIndex:indexPath.row]; 
    ContainerController *c = [[ContainerController alloc] initWithPath:path]; 

    if (c != nil) { 
     [self.navigationController pushViewController:c animated:YES]; 
    } 
    NSLog(@"Selected an item"); 
} 

//old TableView count for epubs 
- (NSInteger) 
    tableView:(UITableView *)tableView 
    numberOfRowsInSection:(NSInteger)section{ 
    return m_paths.count; 
} 

- (void)viewDidLayoutSubviews { 

    //m_table.frame = self.view.bounds; 
    m_coll.frame = self.view.bounds; 
} 

//Collection View Cell Data Allocation 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
        cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)]; 
    //UICollectionViewCell *content = [[UICollectionViewCell alloc] init]; 
    if(indexPath.item %2 == 0){ 
     cell.backgroundColor=[UIColor blueColor]; 
     issue.text = @"Some Text"; 
     issue.textColor = [UIColor greenColor]; 
     issue.textAlignment = NSTextAlignmentCenter; 
    } 
    else { 
     cell.backgroundColor=[UIColor redColor]; 
     issue.text = @"Some Text"; 
     issue.textColor = [UIColor greenColor]; 
     issue.textAlignment = NSTextAlignmentCenter; 
    } 
    NSString *path = [m_paths objectAtIndex:indexPath.row]; 
    NSArray *components = path.pathComponents; 
    NSString *Title = components.lastObject; 

    NSLog(@"Title: %@",Title); 
    NSString *Titletest = components.lastObject; 
    NSInteger comp1 = components.count; 
    NSString *comps = @"components"; 
    NSLog(@"There are: %ld %@", (long)comp1,comps); 
    NSLog(@"Title: %@",Titletest); 
    for (NSInteger i =0; i<15; i++) { 
    NSString * item; 
    item=components[i]; 
    NSLog(@"Component:%ld %@",(long)i,components[i]); 
    } 

    return cell; 
} 

//Collection View Cell Data De-Allocation 
- (void) 
collectionView:(UICollectionView *)collectionView 
numberofItemsInSection:(NSIndexPath *)indexPath{ 

    [collectionView deselectItemAtIndexPath:indexPath animated:YES]; 
    NSString *path = [m_paths objectAtIndex:indexPath.row]; 
    ContainerController *c = [[ContainerController alloc] initWithPath:path]; 

    if(c !=nil){ 
     [self.navigationController pushViewController:c animated:YES]; 
    } 
} 

//Collection 
-(NSInteger) 
    collectionView:(UICollectionView *)collectionView 
    numberOfItemsInSection:(NSInteger)section{ 

    return m_paths.count; 
} 


//Set Collection View Cell Size 
-(CGSize) 
    collectionView:(UICollectionView *) collectionView 
    layout:(UICollectionViewLayout*)collectionViewLayout 
    sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ 


    //Set Landscape size of cells 
    /*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){ 
     CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-360; 
     CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-60; 
     NSLog(@"Is Landscape"); 
     return CGSizeMake(cellWidth, cellHeigt); 
    } 
    //Set Potrait size of cells 
    else{ 
     CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-60; 
     CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-160; 
     NSLog(@"Is Portrait"); 
     return CGSizeMake(cellWidth, cellHeigt); 
    }*/ 

    return CGSizeMake(collectionView.bounds.size.width, collectionView.bounds.size.height); 
} 

//Collection View Cell Position 
- (UIEdgeInsets)collectionView: 
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { 

    if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){ 
     return UIEdgeInsetsMake(150.0,0.0,150.0,0.0); // top, left, bottom, right 
    } 
    else{ 
     return UIEdgeInsetsMake(20.0,0.0,0.0,0.0); // top, left, bottom, right 
    } 
} 

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{ 

    [m_coll performBatchUpdates:nil completion:nil]; 
} 

-(void)viewWillTransitionToSize:withTransitionCoordinator{ 

    [m_coll performBatchUpdates:nil completion:nil]; 
} 

/*-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*) 
collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{ 

    CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing; 
    CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width; 
    NSInteger cellCount = [collectionView numberOfItemsInSection:section]; 
    CGFloat inset = (collectionView.bounds.size.width - ((cellCount-1) * (cellWidth + cellSpacing))) * 0.5; 
    inset = MAX(inset, 0.0); 

    if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){ 

     NSLog(@"Changed to landscape Spacing"); 
     return inset; 

    } 
    else{ 

     return inset; 
    } 

}*/ 
@end 
+0

당신은 사용자 정의 클래스를 생성하고 UICollectionViewCell''대신 사용해야합니다. – vaibhav

+0

그래서'UICollectionViewCell' 커스텀 클래스는 라벨의 세부 사항과 다른 객체를 포함하고 있습니까? –

+0

사용자 정의 클래스를 작성하여 'cell.yourLabel.text = @ "일부 값"및 기타 미리 선언 된 다른 객체를 참조하여 UI 구성 요소를 유지 관리 할 수 ​​있습니다. – vaibhav

답변

0

사용자 정의 collectionViewCell을 사용하는 명확한 예. 이제

#import "CollectionViewCell.h" 

@implementation CollectionViewCell 

@end 

드래그 앤 드롭 :

.H 파일 :

#import <UIKit/UIKit.h> 

@interface CollectionViewCell : UICollectionViewCell 
@property (weak, nonatomic) IBOutlet UILabel *customLabel; 
@end 

하는 .m 파일

UICollectionViewCell의 별도의 클래스의 서브 클래스를 생성 코드 아래 참조 collectionViewviewControllerstoryboard 그런 다음 셀 세트 맞춤 클래스를 선택하고 레이블의 IBOutlet을 아래 이미지를 참조하십시오.

설정 사용자 정의 클래스 :

enter image description here

라벨의 콘센트에 연결 : 드래그 uilabel :경우 스토리 보드

enter image description here

주에서 라벨과 다른 UI 구성 요소를 추가 내부 세포 IBOutlet을 연결하기 전에


이제 viewController 클래스 안에 셀을 구성하십시오. delegate, dataSuorceIBOutlet을 연결하여 collectionView을 올바르게 구성하십시오. 사용하기 전에 cellForItemAtIndexPath 메서드 내 준 MyCustomCell

#import "ViewController.h" 
#import "CollectionViewCell.h" 

@interface ViewController(){ 
    // instance variable deceleration part 
    NSMutableArray *yourArray; 
} 
@end 

@implementation ViewController 

- (void)viewDidLoad{ 
    [super viewDidLoad]; 
    _yourCollView.delegate = self; 
    _yourCollView.dataSource = self; 

    yourArray = [[NSMutableArray alloc] initWithObjects:@"1st cell",@"2nd cell",@"3rd cell",@"4th cell", nil]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

// collection view delegate methods 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 
    return [yourArray count]; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"MyCustomCell" forIndexPath:indexPath]; 

    // configuring cell 
    // cell.customLabel.text = [yourArray objectAtIndex:indexPath.row]; // comment this line if you do not want add label from storyboard 

    // if you need to add label and other ui component programmatically 
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height)]; 
    label.tag = 200; 
    label.text = [yourArray objectAtIndex:indexPath.row]; 

    // this adds the label inside cell 
    [cell.contentView addSubview:label]; 

    return cell; 
} 

//Note: Above two "numberOfItemsInSection" & "cellForItemAtIndexPath" methods are required. 

// this method overrides the changes you have made to inc or dec the size of cell using storyboard. 
- (CGSize)collectionView:(UICollectionView *)collectionView layout: (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    return CGSizeMake(100, 100); 
} 

} // class ends 

설정 (셀을 선택하여) 셀 식별자는 이미지 아래 참조 :

enter image description here

참고 : 흰색에 uilabel의 텍스트 색상을 변경 전에 기본적으로 collectionView이 검은 색으로 표시되기 때문입니다.

여기 이해하시기 바랍니다.

+0

새 UICollectionViewCell을 만들 때 중복 오류가 발생합니다. 나는 또한 UILabel을 .h 파일에 추가 할 수 없다. –

+0

나는 몇 시간을 줄 것이다. 나는 가능한 빨리 대답을 업데이트 할 것이다. – vaibhav

+1

감사합니다. –

1
  1. UICollectionViewCell의 서브 클래스를 생성합니다. 예를 들어 TestCollectionViewCell입니다.
  2. Storyboard에서 셀에 label을 드래그하고이 UICollectionViewCell에 대해 "Custom class"을 생성 한 클래스로 설정하십시오. Reusable identifier을 설정하고 컬렉션보기가 UIViewController 인 경우 및 Delegate을 잊지 말고 collectionView을 입력하십시오.
  3. IBOutlet을 Cell 하위 클래스에 연결하십시오.
  4. numberOfItemsInSection 방법 안에 1 이상의 값을 설정하십시오.
  5. 그런 다음 cellForItemAt에 하위 셀 클래스를 사용하고 레이블에 텍스트를 설정해보십시오.
+0

데이터를 수집하는 타사 프레임 워크의 특성으로 인해 프로그래밍 방식으로 생성해야합니다. 그래서 스토리 보드를 사용하지 마십시오 –

+0

awakeFromNib에서 IBOutlets 및 init 뷰없이 동일한 작업 수행 –

0

당신은 누락 :

[cell.contentView addSubview:issue]; 
관련 문제