iOS App 개발 에서 사용 및 사용자 정의 UITableView Cell 튜 토리 얼

16081 단어 iOSUITableView
UITableView 는 표 형식 으로 데 이 터 를 표시 합 니 다.UITableView 에 대해 서 는 다음 과 같이 주의해 야 합 니 다.
(1)UITableView 는 표 의 보 이 는 부분 을 표시 하고 UITableView Cell 은 표 의 한 줄 을 표시 합 니 다.
(2)UITableView 는 표 의 데 이 터 를 저장 하 는 것 이 아니 라 현재 보 이 는 부분 을 그 릴 수 있 도록 충분 한 데이터 만 저장 합 니 다.
(3)UITableView 는 UITableView Delegate 프로 토 콜 에서 설정 정 보 를 얻 고 UITableView DataSource 프로 토 콜 에서 데이터 정 보 를 얻 습 니 다.
(4)모든 UITableView 가 실 현 될 때 실제로 한 열 만 있 지만 UITableView Cell 에 하위 보 기 를 추가 하여 여러 열 로 보일 수 있 습 니 다.
(5)UITableView 는 두 가지 스타일 이 있 습 니 다.
    ① Grouped:각 조 는 원 사각형 처럼 보인다.
    ② Plain:기본 스타일 로 Indexed 스타일 로 변경 할 수 있 습 니 다.
   
UITableView Cell 인 스 턴 스 사용
아래 의 작은 예 에서 우 리 는 먼저 열 데 이 터 를 표시 한 다음 줄 마다 그림 을 추가 한 다음 에 UITableView Cell 의 네 가지 가 각각 어떤 것 인지 볼 것 이다.마지막 으로 들 여 쓰기 설정,글꼴 크기 수정,줄 높이 등 다른 작업 을 진행 합 니 다.
1.Xcode 4.2 를 실행 하고 Single View 애플 리 케 이 션 을 새로 만 듭 니 다.이름 은 Table Sample 입 니 다.
201641990909065.png (475×194)
2.ViewController.xib 를 누 르 면 Interface Builder 를 사용 하여 보기 에 UITableView 컨트롤 을 추가 하고 전체 보 기 를 덮어 씁 니 다.
201641990939756.jpg (951×510)
3.새로 추 가 된 UITableView 컨트롤 을 선택 하고 Connection Inspector 를 열 고 delegate 와 datasource 를 찾 습 니 다.오른쪽 에 있 는 동그라미 에서 File's Owner 아이콘 까지 끌 어 올 립 니 다.
201641990956899.jpg (837×192)
4.ViewController.h 를 누 르 면 코드 를 추가 합 니 다.

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *listData;
@end
5.ViewController.m 을 누 르 고 코드 를 추가 합 니 다.
5.1@implementation 뒤에 코드 추가:

@synthesize listData;
5.2 view DidLoad 방법 에 코드 추가:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSArray *array = [[NSArray alloc] initWithObjects:@"Tree", @"Flower",
                      @"Grass", @"Fence", @"House", @"Table", @"Chair",
                      @"Book", @"Swing" , nil];
    self.listData = array;
}
5.3 viewd Unload 방법 에 코드 추가:

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.listData = nil;
}
5.4@end 전에 코드 추가:

#pragma mark -
#pragma mark Table View Data Source Methods
//
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return [self.listData count];
}

//
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             TableSampleIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:TableSampleIdentifier];
    }
   
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [listData objectAtIndex:row];
 return cell;
}

위의 두 번 째 방법 중,

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];
이 문 구 는 식별 자 TableSampleIdentifier 에 따라 현재 다시 사용 할 수 있 는 UITableViewCell 을 찾 습 니 다.현재 보 이 는 영역 에서 한 줄 이 미 끄 러 지면 해당 하 는 UITableView Cell 대상 을 다시 사용 하면 메모리 와 시간 을 절약 할 수 있 습 니 다.
단 어 를 실행 한 후 cell 이 nil 이면 하 나 를 더 만 들 고 식별 자 를 Table Sample Identifier 로 설정 합 니 다.

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
여기 서 UITableView Cell Style Default 는 UITableView Cell 스타일 을 나타 내 는 상수 입 니 다.그 밖 에 다른 스타일 도 있 습 니 다.나중에 사용 할 것 입 니 다.
인자(NSIndexPath*)indexPath 를 주의 하 십시오.줄 번호 row 와 일부 번호 section 을 합 쳐[indexPath row]를 통과 합 니 다.줄 번호 가 져 오기.다음 셀 에 텍스트 설정:

cell.textLabel.text = [listData objectAtIndex: row];
6.실행:
201641991022472.png (284×405)
7.줄 마다 그림 추가:
7.1 이미지 자원 을 프로젝트 에 추가 합 니 다.프로젝트 에 끌 어 다 놓 으 면 앞의 글 에서 언급 되 었 습 니 다.
7.2 cellForRow AtIndexPath 방법의 return 문 구 를 추가 하기 전에 코드 를 추가 합 니 다.

UIImage *image = [UIImage imageNamed:@"blue.png"];
cell.imageView.image = image;
UIImage *highLighedImage = [UIImage imageNamed:@"yellow.png"];
cell.imageView.highlighedImage = highLighedImage;
7.3 운행,효 과 는 다음 과 같다.
201641991042257.png (284×405)
줄 마다 왼쪽 에 그림 이 한 장 씩 나타 나 는 것 을 볼 수 있다.어떤 줄 을 선택 하면 그림 이 변 합 니 다.
8.줄 의 스타일 설정:
UITableView Cell 스타일 의 상수 는 다음 과 같 습 니 다.

UITableViewCellStyleDefault
UITableViewCellStyleSubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
이 몇 가지 스타일 의 차 이 는 주로 Image,Text Label 과 Detail Text Label 에 나타난다.
스타일 을 구현 하기 위해 cellForRow AtIndexPath 방법의 return 문 구 를 추가 하기 전에 코드 를 추가 합 니 다.

cell.detailTextLabel.text = @"Detail Text";
그리고

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
위 에서 언급 한 네 가지 스타일 상수 로 변경 하고 실행 합 니 다.효 과 는 다음 과 같 습 니 다.
201641991102458.png (288×120)
UITableViewCellStyleDefault  
201641991118771.png (288×120)
UITableViewCellStyleSubtitle
201641991134672.png (288×120)
UITableViewCellStyleValue1
201641991151227.png (288×120)
UITableViewCellStyleValue2
    
9.들 여 쓰기 설정:
모든 줄 의 스타일 을 UITableView CellStyleDefault 로 바 꾼 다음@end 전에 코드 를 다음 과 같이 추가 합 니 다.

#pragma mark Table Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    return row;
}
다음 그림 과 같이 첫 번 째 row 줄 을 row 로 축소 합 니 다.
201641991212833.png (280×400)
10.조종 줄 선택:
@end 전에 코드 추가:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    if (row%2 == 0) {
        return nil;
    }
    return indexPath;
}
위의 방법 은 어떤 줄 을 선택 하기 전에 실행 합 니 다.우 리 는 이 방법 에 우리 가 원 하 는 조작 을 추가 할 수 있 습 니 다.여기 서 우리 가 실현 하 는 것 은 선택 한 줄 번호(0 부터 계산)가 짝수 라면 선택 을 취소 하 는 것 이다.
@end 전에 코드 추가:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    NSString *rowValue = [listData objectAtIndex:row];
   
    NSString *message = [[NSString alloc] initWithFormat:
                         @"You selected %@", rowValue];
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Row Selected!"
                          message:message
                          delegate:nil
                          cancelButtonTitle:@"Yes I Did"
                          otherButtonTitles:nil];
    [alert show];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
어떤 줄 을 선택 하면 우리 가 선택 한 것 을 표시 하기 위해 Alert 를 팝 업 합 니 다.
실행 하면 0,2 등 줄 을 선택 할 수 없습니다.홀수 줄 선택 시 알림 팝 업:
201641991230749.jpg (280×400)
그리고 알림 상 자 를 닫 은 후에 선택 한 줄 도 선택 이 취소 되 었 습 니 다.

[tableView deselectRowAtIndexPath:indexPath animated:YES];
11.글꼴 크기 와 표 줄 높이 설정:
11.1 cellForRow AtIndexPath 방법 에서 return 전에 코드 를 추가 하여 글꼴 과 크기 를 설정 합 니 다.

cell.textLabel.font = [UIFont boldSystemFontOfSize:50];
11.2@end 전에 코드 를 추가 하여 줄 높이 설정 에 사용 합 니 다.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}
실행,효과 보기:
201641991250465.png (259×171)
사용자 정의 가능 한 UITableViewCell
UITableView 의 강력 함 은 UITableView Cell 셀 을 임의로 사용자 정의 할 수 있 는 셀 에서 비롯 됩 니 다.일반적으로 UITableView 의 Cell 은 동적 입 니 다.사용 과정 에서 하나의 Cell 탱크 를 만 듭 니 다.각 cell 의 높이(즉,tableView:height ForRow AtIndexPath:반환 값)와 화면 높이 에 따라 화면 에 몇 개의 cell 을 표시 할 수 있 습 니 다.한편,사용자 정의 Table View Cell 은 코드 로 이 루어 지 거나 IB 로 nib 파일 을 편집 하여 두 가지 방식 을 실현 하 는 것 이 아니 라 본 고 는 주로 코드 를 수집 하 는 방식 으로 각종 cell 사용자 정 의 를 실현 한다.
1.셀 높이 를 어떻게 동적 으로 조정 합 니까?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.tag = 1;
        label.lineBreakMode = UILineBreakModeWordWrap;
        label.highlightedTextColor = [UIColor whiteColor];
        label.numberOfLines = 0;
        label.opaque = NO; // Opaque
        label.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:label];
        [label release];
    }
 
    UILabel *label = (UILabel *)[cell viewWithTag:1];
    NSString *text;
    text = [textArray objectAtIndex:indexPath.row];
    CGRect cellFrame = [cell frame];
    cellFrame.origin = CGPointMake(0, 0);
 
    label.text = text;
    CGRect rect = CGRectInset(cellFrame, 2, 2);
    label.frame = rect;
    [label sizeToFit];
    if (label.frame.size.height > 46) {
        cellFrame.size.height = 50 + label.frame.size.height - 46;
    }
    else {
        cellFrame.size.height = 50;
    }
    [cell setFrame:cellFrame];
 
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

2.Table Separerator 분할 선 을 그림 으로 정의 하 는 방법
일반적으로[tableView setSeparatorColor:[UIColor red Color]와 유사 한 것 을 이용 합 니 다.문 구 는 cell 중간 분할 선의 색 을 수정 할 수 있 습 니 다.그러면 어떻게 하나의 그림 을 분할 선 배경 으로 합 니까?다음 과 같이 시도 할 수 있 습 니 다:
방법 1:
셀 separator Color 를 clear 로 설정 한 다음 그림 의 분할 선 을 사용자 정의 custom cell 에 추가 합 니 다.
방법 2:
cell 에 픽 셀 의 imageView 를 추가 한 후 그림 을 불 러 오고 tableView 를 설정 합 니 다.separatorStyle=UITableView CellSeparatorStyleNone
3.첫 번 째 셀 과 위 탐색 표시 줄 간격 을 사용자 정의 합 니 다.

tableView.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,5,20)] autorelease];
4.UITableViewCell 의 accessory 스타일 사용자 정의
기본 accessory Type 속성 은 네 가지 수치 가 있 습 니 다:UITableView CellAccessory None,UITableView CellAccessory Disclosure Indicator,UITableView CellAccessory DetailDisclosure Button,UITableView CellAccessory Checkmark.사용자 정의 첨부 단추 의 다른 스타일 을 사용 하려 면 UITableView 의 accessory View 속성 을 사용 하여 지정 해 야 합 니 다.

UIButton *button;
if(isEditableOrNot) {
    UIImage *image = [UIImage imageNamed:@"delete.png"];
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0,0.0,image.size.width,image.size.height);
    button.frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;
}else{
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;
}
이 코드 는 첨부 단추 두 가지 상태 에서 만 스타일 을 정의 합 니 다.문 제 는 현재 이 사용자 정의 첨부 단추 의 이벤트 가 사용 되 지 않 는 다 는 것 입 니 다.즉,이 벤트 는 UITable View Delegate 의 accessory Button Tapped ForRow With IndexPath 방법 에 전달 되 지 않 습 니 다.우리 가 상기 코드 에 다음 과 같은 문 구 를 추가 할 때:
[button addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
이후,모든 첨부 버튼 의 클릭 사건 을 포착 할 수 있 지만,우 리 는 도대체 어떤 줄 의 첨부 버튼 이 클릭 동작 을 일 으 켰 는 지 구별 할 수 없습니다!addTarget:방법 은 최대 두 개의 인 자 를 전달 할 수 있 기 때 문 입 니 다.target 과 event.이 두 인 자 는 모두 각자 의 용도 가 있 습 니 다(target 은 사건 의뢰 대상 을 가리 키 고 event 는 발생 하 는 사건 을 가리 킵 니 다).코코아 프레임 만 으로 는 할 수 없 을 것 같 습 니 다.
      그러나 이벤트 인 자 를 이용 하여 사용자 정의 btnClicked 방법 에서 이벤트 가 UITableView 의 어떤 cell 에서 발생 하 는 지 판단 할 수 있 습 니 다.UITableView 는 매우 중요 한 방법 이 있 기 때문에 indexPath ForRow AtPoint 는 터치 가 발생 하 는 위치 에 따라 터치 가 어느 cell 에서 발생 하 는 indexPath 를 되 돌 릴 수 있 습 니 다.또한 이벤트 대상 을 통 해 보기 에 있 는 모든 터치 의 위 치 를 얻 을 수 있 습 니 다.

// , accessory tapped
- (void)btnClicked:(id)sender event:(id)event
{
     NSSet *touches = [event allTouches];
     UITouch *touch = [touches anyObject];
     CGPoint currentTouchPosition = [touch locationInView:self.tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
     if(indexPath != nil)
     {
         [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
     }
}
이렇게 하면 UITableView 의 accessory Button Tapped ForRow With IndexPath 방법 이 트리거 되 고 indexPath 인 자 를 얻 을 수 있 습 니 다.이 indexPath 인 자 를 통 해 우 리 는 도대체 어느 줄 의 첨부 버튼 에 터치 이벤트 가 발생 했 는 지 구분 할 수 있 습 니 다.

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    int  *idx = indexPath.row;
   //
}

좋은 웹페이지 즐겨찾기