我无法对齐中心单元格文本。我想知道它是否可能是XML的问题?
我创建了一个UILabel,将它与中心对齐并将其添加到单元格中。这是我的代码示例:
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *lblMenuTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 250, 30)];
NSString *sectionString = [NSString stringWithFormat:@"%@",[[arrDataSection objectAtIndex:indexPath.row] valueForKey:kCasesName]];
[lblMenuTitle setText:sectionString];
[lblMenuTitle setTextAlignment:UITextAlignmentCenter];
lblMenuTitle.font = [UIFont boldSystemFontOfSize:18.0];
[lblMenuTitle setNumberOfLines:0];
[lblMenuTitle setTag:[[NSString stringWithFormat:@"1%d",indexPath.row] intValue]];
[lblMenuTitle setLineBreakMode:UILineBreakModeWordWrap];
[lblMenuTitle setBackgroundColor:[UIColor clearColor]];
[cell addSubview:lblMenuTitle];
CGRect frame;
CGSize size;
frame = CGRectMake(20, 5, 250, 30);
size = [lblMenuTitle.text sizeWithFont:[UIFont systemFontOfSize:18.0]
constrainedToSize:CGSizeMake(frame.size.width, 9999)
lineBreakMode:UILineBreakModeWordWrap];
frame.size = CGSizeMake(size.width+20, size.height);
lblMenuTitle.frame = frame;
}
return cell;
答案 0 :(得分:4)
您计算文字的大小(size = [lblMenuTitle.text sizeWithFont:…]
)并修改lblMenuTitle
标签的框架,使其宽度为文字大小(+ 20px)......
因此,文本不在单元格的中心是很正常的:文本在UILabel([lblMenuTitle setTextAlignment:UITextAlignmentCenter]
)中居中,但标签的宽度与文本本身相同!因此,如果文本宽度为100px,则您的标签宽度为120px ......但其帧的原点仍为x = 20!
保持标签宽度与单元格宽度一样大,让文本对齐完成将文本居中放入标签的工作,或者如果您仍希望调整标签的宽度与文本相同,则将其居中框架也是(例如lblMenuTitle.center = cell.center
)