Swift:将UILabel文本对齐在顶部而不是中间

时间:2015-08-03 01:38:15

标签: ios swift uilabel text-alignment

我希望UILabel从顶部开始,即使文本很短也是如此 NSTextAlignment无效

enter image description here

cell.textContent.text = comments[indexPath.row]
cell.textContent.textAlignment = 




func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //post's section == 0

    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCellWithIdentifier("postCID", forIndexPath: indexPath) as! postCell
        cell.usernameLabel.text = "Steve Paul Jobs"
         cell.time.text = "9:42 PM"
         cell.commentsLabelCount.text = "12 Comments"
         cell.textContent.text = "Return the number of rows in the sectioReturn the number of rows in the sectioReturn the number of rows in the sectioReturn the number of rows in the sectioReturn the number of rows in the sectioReturn the number of rows in the sectio"

        cell.layoutSubviews()

    }

        let cell = tableView.dequeueReusableCellWithIdentifier("commentCID", forIndexPath: indexPath) as! commentCell
        // Configure the cell...
      cell.layoutSubviews()

    cell.usernameLabel.text = "Steve Paul Jobs"
    cell.time.text = "9:42 PM"
    cell.textContent.text = comments[indexPath.row]
     cell.textContent.textAlignment = NSTextAlignment.Left


        return cell



}


import UIKit

class commentCell: UITableViewCell {
    @IBOutlet weak var textContent: UILabel!
    @IBOutlet weak var time: UILabel!
    @IBOutlet weak var userImage: UIImageView!
    @IBOutlet weak var usernameLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    userImage.layer.cornerRadius = 2
    userImage.clipsToBounds = true

}
override func layoutSubviews() {
    super.layoutSubviews()
    textContent.sizeToFit()
}

4 个答案:

答案 0 :(得分:49)

在Storyboard中使用自动布局非常简单:

enter image description here

label.numberOfLines = 0;

答案 1 :(得分:12)

在您的自定义UITableViewCell类中添加以下内容:

override func layoutSubviews() {
    super.layoutSubviews()
    textContent.sizeToFit()
}

这里是一个示例项目的链接,只是想要引用单元格和表格的设置方式: https://mega.nz/#!ZoZCgTaA!7gvkRw4pwecMfDXrNW_7jR2dKe2UR9jPsq9tp_CRIcU

答案 2 :(得分:6)

这可以通过自动布局轻松完成。确保文本标签位于正确的视图中。

  1. 确保文本标签的行数设置为0
  2. number of lines is zero

    1. 选择文本标签并固定顶部,左侧和右侧约束。点击底部的“添加3个约束”按钮。
    2. enter image description here

      1. 更新您的相框(以查看故事板中更新的路线)。
      2. enter image description here

答案 3 :(得分:6)

在您的自定义UITableViewCell类中添加以下内容:

override func layoutSubviews() {
    super.layoutSubviews()
    self.contentView.layoutIfNeeded() //This is the solution for :changed only after I tap the each cell
    textContent.sizeToFit()
}