티스토리 뷰

발생일: 2016.04.40

키워드: tag, interface builder, 태그 속성, 태그 프로퍼티, viewWithTag

문제:
xib 파일에 UIView 의 태그 프로퍼티를 할당하고 코드에서 해당 뷰를 가져오려고 한다.


해결책:
Table View Programming Guide for iOS에는 태그를 사용해 테이블셀의 레이블을 설정하는 예제가 있다.

인터페이스 빌더의 Attributes inspector 에서 Tag 항목에 값을 설정해주면 된다.



코드에서는 아래와 같이 viewWithTag: 로 설정한 태그 값으로 가져올 수 있다.


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    UILabel *label;

    label = (UILabel *)[cell viewWithTag:1];
    label.text = [NSString stringWithFormat:@"%d", indexPath.row];

    label = (UILabel *)[cell viewWithTag:2];
    label.text = [NSString stringWithFormat:@"%d", NUMBER_OF_ROWS - indexPath.row];

    return cell;
}



논의:
- viewWithTag: 는 현재 뷰로부터 시작해 모든 자식을 리컬시브하게 검색하며, 첫 번째 매칭된 UIView 를 리턴한다.
- tag 프로퍼티를 데이터를 저장하는 용도로 사용하지 않도록 주의한다.
    자세한 내용은 iOS: UIVIew 의 tag 프로퍼티 사용 시 주의사항 포스트 참고


반응형
댓글
공지사항