Swift : align UILabel text in the top rather in the middle

I want the UILabel to start from the top even if the text is short it seems that NSTextAlignment doesn't work

在这里输入图像描述

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()
}

In your custom UITableViewCell class add this:

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

Here's a link to a sample project just incase you want to reference how the cell and table is set up: https://mega.nz/#!ZoZCgTaA!7gvkRw4pwecMfDXrNW_7jR2dKe2UR9jPsq9tp_CRIcU


Using Auto Layout in Storyboard will be very simple:

在这里输入图像描述

and

label.numberOfLines = 0;

This can easily be done with auto layout. Ensure your text label is in the correct view.

  • Ensure your text label's number of lines is set to 0
  • Select your text label and pin the top, left, and right constraints. Hit the 'Add 3 Constraints' button at the bottom.
  • 在这里输入图像描述

  • Update your frames (to see the updated alignment in storyboard).
  • 在这里输入图像描述

    链接地址: http://www.djcxy.com/p/28192.html

    上一篇: 垂直对齐UILabel

    下一篇: Swift:在顶部而不是中间对齐UILabel文本