【发布时间】:2016-03-27 16:27:59
【问题描述】:
在自定义单元格中获取正确的标签宽度时遇到问题。 这是我在故事板中的单元格:
创建表格时,我知道调用cellForRowAtIndexPath时,单元格刚刚创建,还没有添加到UITableView中,所以标签的宽度是304px。这会导致如下结果:
滚动后,单元格已添加到 UITableView 中,可以正确显示,标签宽度为 164px。
在添加到 UITableView 之前,有没有办法知道单元格/标签的确切宽度?
标签上的约束:Leading、Trailing、Top 和 Height
以下是源代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ArticleCell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleCell
let item = array.objectAtIndex(indexPath.row) as! Article
cell.showDataForArticle(item, dateFormatter: dateFormatter)
return cell
}
func showDataForArticle(article: Article, dateFormatter: NSDateFormatter) {
self.titleLbl.text = article.articleTitle
titleHeightConstraint.constant = titleLbl.requiredHeight() <--- where problem happens
self.thumbnailImgView.imageLink(article.articleThumbnailLink!)
self.authorLbl.text = article.articleCreator
self.dateLbl.text = dateFormatter.stringFromDate(article.articlePubDate!)
}
extension UILabel {
func requiredHeight() -> CGFloat {
let frame = CGRectMake(0, 0, self.frame.size.width, CGFloat.max)
let label: UILabel = UILabel(frame: frame)
label.numberOfLines = 0
label.lineBreakMode = .ByWordWrapping
label.font = self.font
label.text = self.text
label.sizeToFit()
return label.frame.size.height
}
【问题讨论】:
-
尝试子类化 tableview 单元格并在 layoutsubviews 方法或 initWithStyle 方法中找出边界。
-
我推荐你使用自动布局。
-
显示您的 cellforRow 代码,是的,使用自动布局..
-
我当然用过自动布局 :)
-
我已经在上面添加了我的代码
标签: ios swift uitableview uilabel