如何以编程方式更改detailTextLabel高度

时间:2017-10-14 05:14:21

标签: ios swift uitableview uilabel height

我将一个数组编程为tableView。当单元格为detailTextLabel使用多行时,行之间的空间很小。我想知道是否有任何方法可以通过编程方式增加此高度?这是我用于数组的示例代码。

cell.textLabel?.text = self.filtered[indexPath.row].coptic
cell.detailTextLabel?.text = self.filtered[indexPath.row].english
cell.textLabel?.font = UIFont(name:"CS Avva Shenouda", size:30)
cell.detailTextLabel?.font = UIFont(name: "Constantia", size:25)
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.textColor = UIColor.darkGray

return cell

2 个答案:

答案 0 :(得分:2)

我只是把我的逻辑,而不是整个代码。 您可以通过以下代码获得字符串的高度

func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.height)
    }

更改cellForRowAtIndexPath方法

cell.detailTextLabel?.numberOfLines = 0 
let height = height(withConstrainedWidth:200, font:YourFont) // change width and font as per your requirement 
cell.detailTextLabel?.frame = CGRect(x: cell.detailTextLabel?.frame.origin.x, y: cell.detailTextLabel?.frame.origin.y, width: cell.detailTextLabel?.frame.size.width, height: height)

您可以根据detailTextLabel height

管理单元格高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
   return 50 // You should put your code or logic that dynamic height based on heigh of label.
}

答案 1 :(得分:2)

表视图需要具有estimatedRowHeight和tableView高度作为UITableViewAutomaticDimension。