내 테스트 응용 프로그램에서는 가변 높이 테이블 셀을 맨 위에 단일 픽셀 선으로 스타일을 지정하고 싶습니다. 이것은 내가 사용하고있는 드로잉 코드이지만 작동하지 않습니다.가변 높이 UITableViewCell의 한 픽셀 경계가 여러 픽셀로 나오지 않게하려면 어떻게해야합니까?
// In OneLine.m
- (void)drawRect:(CGRect)rect {
// Drawing code
[[UIColor blackColor] set];
UIRectFill(rect);
[[UIColor whiteColor] set];
UIRectFill(CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 1));
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
self.contentMode = UIViewContentModeTop;
}
return self;
}
유일한 문제는 내가 변수 높이의 흰색 선으로 끝낼 것입니다 :
// In OneLine.h
@interface OneLine : UIView {}
@end
그리고 드로잉 코드 :
다음은 헤더에 대한 코드입니다. 항상 1 픽셀 높은 것은 아닙니다. 내가 도대체 뭘 잘못하고있는 겁니까? 테스트 셀을 제공하는 데 사용되는 테이블 뷰 컨트롤러가 있습니다. 다음과 같이 초기화합니다.
// In MyTable.h
#import <UIKit/UIKit.h>
@interface MyTable : UITableViewController {
NSMutableArray *data;
}
@end
기본 템플릿에서 추가/변경된 메소드 만 사용하십시오.
// In MyTable.m
#import "MyTable.h"
#import "OneLine.h
@implementation MyTable
- (id)initWithStyle:(UITableViewStyle)style {
if (self = [super initWithStyle:style]) {
srand(time(NULL));
data = [[NSMutableArray alloc] init];
for (size_t index = 0; index < 200; ++index) {
// Each cell has a different height betweet 40 and 50 pixels tall.
[data addObject:[NSNumber numberWithInt:(rand() % 10) + 40.5]];
}
}
return self;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
cell.contentView.contentMode = UIViewContentModeTop;
OneLine *view = [[OneLine alloc] initWithFrame:cell.contentView.bounds];
[cell.contentView addSubview:view];
}
// Set up the cell...
OneLine *view = [cell.contentView.subviews objectAtIndex:[cell.contentView.subviews count] - 1];
// Build the correct frame
view.frame = CGRectMake(0, 0, cell.contentView.bounds.size.width, [MyTable tableView:(UITableView*)self.view heightForRowAtIndexPath:indexPath]);
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSNumber *num = (NSNumber*) [data objectAtIndex:indexPath.row];
return [num intValue];
}
@end
이 코드의 모든
은 (40 내지 50 픽셀 높이 임의 높이의 200 개 세포와 테이블 뷰 컨트롤러를 만듭니다.
또한, drawRect : method의 rect 매개 변수는 뷰의 전체 rect가 아니며 유효하지 않은 영역의 rect이므로 다시 칠해야합니다 (setNeedsDisplayInRect 참조). 대부분의 경우 [self bounds]와 동일하지만 setNeedsDisplayInRect :가 호출되면 그럴 수 없습니다 – rpetrich