В моем тестовом приложении я хочу стилизовать ячейки таблицы переменной высоты с одной линией пикселя вверху. Это код рисования, который я использую, но он не работает.
Ниже приведен код для заголовка:
// In OneLine.h
@interface OneLine : UIView {}
@end
и код чертежа:
// 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 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
Весь этот код просто создает контроллер табличного представления с 200 ячейками произвольной высоты (высотой от 40 до 50 пикселей.