在UITableViewCell中动态调整UILabel?
我想动态调整UILabel中的行数。 例如,可能有一个长字符串或一个短字符串。 如果少于10个字符,则应该有一行。 如果有10-20个字符,则应为两行。 这个UILabel位于UITableViewCell内。 目前,如果有一个长字符串,那么UILabel只会在空格不足的地方显示“…”,因此字符串被截断。 我怎样才能防止这种情况发生?
尝试:
nameOfLabel.numberOfLines = 0
0应该是动态的。
标签和label.numberOfLine = 0的左上方右边的构造使其根据动态内容动态resize。
首先从Storyboard为该UILabel设置numberOfLines为0
比设置UITableView的估计高度
self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 108.0
比添加heightForRowAt方法
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
希望它有所帮助!
- 分配并实现tableview dataSource和delegate
- 将
UITableViewAutomaticDimension
分配给rowHeight和estimatedRowHeight - 实现delegate / dataSource方法(即
heightForRowAt
并向其返回值UITableViewAutomaticDimension
)
–
目标C:
// in ViewController.h #import @interface ViewController : UIViewController @property IBOutlet UITableView * table; @end // in ViewController.m - (void)viewDidLoad { [super viewDidLoad]; self.table.dataSource = self; self.table.delegate = self; self.table.rowHeight = UITableViewAutomaticDimension; self.table.estimatedRowHeight = UITableViewAutomaticDimension; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewAutomaticDimension; }
迅速:
@IBOutlet weak var table: UITableView! override func viewDidLoad() { super.viewDidLoad() // Don't forget to set dataSource and delegate for table table.dataSource = self table.delegate = self // Set automatic dimensions for row height table.rowHeight = UITableViewAutomaticDimension table.estimatedRowHeight = UITableViewAutomaticDimension } // UITableViewAutomaticDimension calculates height of label contents/text func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
对于UITableviewCell中的标签实例
- 设置行数= 0(&换行模式=截断尾部)
- 设置相对于其superview / cell容器的所有约束(顶部,底部,右侧)。
- 可选 :如果您希望标签覆盖最小垂直区域,即使没有数据,也可以设置标签的最小高度。
注意 :如果您有多个具有动态长度的标签(UIElements),应根据其内容大小进行调整:调整要以更高优先级展开/压缩的标签的“内容拥抱和压缩阻力优先级”。
您需要为tableview单元格的标签前导,尾随,顶部和底部提供约束,如下所示…
还将标签的行数设置为零,将换行模式设置为自动换行。
在主视图控制器中添加此行…
self.tableView.estimatedRowHeight = UITableViewAutomaticDimension
上面的行根据其内容自动计算单元格高度。