ios - 将文本对齐到 TableView 中单元格左上角的简单方法?

标签 ios swift

我在 TableView 的单元格中有一些文本,我想将其显示在单元格的左上角。

将文本左对齐非常简单,使用:

cell.textLabel?.textAlignment = NSTextAlignment.left

但是,我找到的所有将文本垂直对齐到顶部的解决方案都非常复杂。

有没有一种我不知道的简单方法可以做到这一点?

This is my layout

这是我的布局,我没有自定义单元格。

最佳答案

如下声明单元格:

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! UserCell

       // to do: additional code
        return cell
    }

然后定义 UserCell 类:

class UserCell: UITableViewCell {

    override func layoutSubviews() {
        super.layoutSubviews()
        textLabel?.frame = CGRect(x: 0, y: 0, width: textLabel!.frame.width, height: textLabel!.frame.height)
        textLabel?.backgroundColor = UIColor.red //only for demonstration
        textLabel?.sizeToFit()
        //detailtextlabel code
    }
}

我认为您正在寻找如下输出:

enter image description here

关于ios - 将文本对齐到 TableView 中单元格左上角的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54421600/

相关文章:

ios - Xcode 错误 : PBXCp error: couldn't create directory

iphone - AVAudioRecorder 不适用于 iPhone 5S

ios - 我可以将 p8 APNs Auth Key 转换为 pem 文件吗?

swift - 如何在 Swift 中将 NSUserDefaults 与属性 getter 和 setter 一起使用?

swift - SELECT * 行为异常 - Swift SQLite FMDB

ios - 如何快速在MKMapview上显示MKPinAnnotationView

ios - ip camera feed 到 IOS 应用程序如何允许全局连接?

ios - Xcode不建立更改的文件

ios - 如何更改 NSLocationUsageDescription 中的文本

swift - 传递当前的 SKScene 实例 Swift