Objective c addSubView在UITableView上无法正常工作
此代码应在单元格上画一条线:Objective c addSubView在UITableView上无法正常工作,objective-c,uitableview,Objective C,Uitableview,此代码应在单元格上画一条线: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (nil==cell){ cell = [[UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (nil==cell){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
NSString *currentCourseName=[courseKeys objectAtIndex:[indexPath row]];
[[cell textLabel] setText:currentCourseName];
NSLog(currentCourseName);
CGSize size = [cell.textLabel.text sizeWithFont:cell.textLabel.font];
CGFloat y = cell.contentView.frame.size.height / 2;
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(5,y,size.width, 3)];
line.backgroundColor = [UIColor redColor];
[cell.textLabel addSubview:line];
return cell;
}
但我似乎必须滚动几次才能看到红线。
我发现您的代码中有两个问题 首先
CGFloat y=cell.contentView.frame.size.height/2
创建单元格时,contentView
的框架是什么?如果要将子视图添加到标签,请使用标签的高度
CGSize size = [cell.textLabel.text sizeWithFont:cell.textLabel.font];
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(5, cell.textLabel.bounds.size.height / 2.0f - 1.5f, size.width, 3)];
line.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
第二
[cell.textlab addSubview:line]代码>
如果重复使用单元格,则在已有行的情况下向单元格添加行。首先检查子视图计数
if (cell.textLabel.subviews.count == 0) {
[cell.textLabel addSubview:line];
}
我认为您要在其中添加的视图,而不是在-(UITableViewCell*)tableView:(UITableView*)tableView cell for rowatindexpath:(nsindepath*)indepath
方法中添加,请尝试使用自定义单元格概念。在我的UITableView
中解决了这个问题
UILabel的No visible@interface声明了选择器“contentView:”尝试使用[cell.contentView addSubview:line]将行放入UItableView中的位置??然后在需要任何条件的位置??感谢您的回答,对于第一个问题,这是行的y位置,没有关系。但是第二个问题,是的,你是对的。@Maysamy
位置可能才是真正重要的。如果您的y
计算不正确,导致您的行超出标签的边界,该怎么办NSLog
查看您的图幅,您会发现问题所在。请注意,创建单元格和重用单元格时,contentView
的大小会有所不同。请在返回方法的单元格之前,NSLog
表的框架、内容视图、文本标签和行的大小。这肯定会起作用,但只是一种变通方法。学习如何编程的方法是理解bug。
if (cell.textLabel.subviews.count == 0) {
[cell.textLabel addSubview:line];
}