我是Objective-C和iPhone开发的新手,在尝试将文本放在表格单元格中时遇到了一个问题.我搜索了谷歌,但解决方案是针对旧的SDK错误已修复,这些对我不起作用.
一些代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = @"Please center me";
cell.textLabel.textAlignment = UITextAlignmentCenter;
return cell;
}
Run Code Online (Sandbox Code Playgroud)
以上内容并非文本的中心.
我也试过了willDisplayCell方法:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.textLabel.textAlignment = UITextAlignmentCenter;
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一些旧的解决方案:
UILabel* label = [[[cell contentView] subviews] objectAtIndex:0];
label.textAlignment = UITextAlignmentCenter;
return cell;
Run Code Online (Sandbox Code Playgroud)
这些都不会对文本对齐产生任何影响.我已经没有想法了,任何帮助都会受到最高的赞赏.
提前干杯.
我正在开发ios应用程序最小ios 5,我刚刚与uilabels发生了一个奇怪的问题.或者也许是我遗漏了一些明显 无论如何,我遇到的问题是我有一个uilabel,它将以文本对齐为中心.所有在ios 5上工作正常,但在ios 6上它总是左对齐.我看到旧的uilabel文本对齐方式已经弃用了,设置它应该可以工作.
self.topComment.textAlignment = NSTextAlignmentCenter;
Run Code Online (Sandbox Code Playgroud)
但即便如此,它仍然只在ios 5上居中对齐并在ios 6上左对齐.我确实有一些代码可以调整标签中文本的字体大小,以使其适合最小和最大尺寸.
UIFont *font = self.topComment.font;
for(int i = maxFont; i > minFont; i--)
{
// Set the new font size.
font = [font fontWithSize:i];
CGSize constraintSize = CGSizeMake(self.topComment.frame.size.width, 1000);
CGSize labelSize = [topString sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
if(labelSize.height <= self.topComment.frame.size.height ) {
fits = YES;
break;
}
//self.topComment.text = topString;
}
self.topComment.font = font;
self.topComment.text = topString;
Run Code Online (Sandbox Code Playgroud)
所以这是我对标签做的唯一的事情,但它始终在ios 6中保持对齐.重要的是要注意,如果我放入带有文本和中心对齐的uilabel并且不使用上面的代码,那么它将以两者为中心ios 5和6.