为此,您必须限制 UITableViewCell 的默认 textLabel 的宽度或将新的 UILabel 添加到单元格。
你有两个选择
1)不要使用单元格的默认textLabel,创建新的UILabel并将其添加为tableview单元格的子视图。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell using custom cell
//restrict width here while creating label (change 40 to what you want)
UILabel *tempLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,0,40,20)];
tempLabel.text=@"The text you want to assign";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[[cell contentView] addSubview:tempLabel];
}
return cell;
}
2)或者第二种方法是更改默认 textLabel 的宽度,为此您必须创建继承 UITableViewCell 的新子类,并在子类覆盖方法(void)layoutSubView 中并在该方法中更改宽度(通过试错法进行)
使用以下 .h 和 .m 文件创建新类
////CustomCell .h file
#import <UIKit/UIKit.h>
@interface CustomCell : UITableViewCell
@end
////CustomCell .m file
#import "CustomCell.h"
@implementation CustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
-(void)layoutSubviews{
[super layoutSubviews];
CGRect tempFrame=self.textLabel.frame;
//whatever you want to set
tempFrame.width=30;
self.textLabel.frame=tempFrame;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
或另一种选择(更好的一种)
3)创建自定义表格视图单元格
自定义 tableview 单元格教程
并且对于在 UILabel 的末尾有 ... ,有 UILabel 的属性 truncateTail 。你可以使用它。