Swift 3.0 中的 cellForRowAt 中的文本向右对齐

textAlignent to right in cellForRowAt in Swift 3.0

我无法让文本与 table 视图的右侧对齐。我的代码将文本对齐方式设置为右对齐,但它仅在超过 1 行时才对齐文本。这是我的 cellforRowAt 代码

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
    cell.textLabel?.text = self.messages[indexPath.row]
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.textAlignment = .right
    return cell
}

我该如何解决这个问题?

您使用的是 UITableViewCell 样式的字幕,对吗?这种样式无论出于何种原因都不允许您覆盖文本标签的对齐方式。

为了解决这个问题,你可以做一个简单的 UITableViewCell 的子类,在相同的位置有一个标签。

我们把单元格的样式改成default:

let cell = UITableViewCell(style: .default, reuseIdentifier: cellId)

我在故事板中创建了一个字幕单元格,我意识到 textLabel 的大小与其内容相符。所以不能对齐textLabel的文字。但是你可以用基本单元格来做到这一点,它的大小与单元格匹配。