简体   繁体   中英

Vertically align text within a UILabel (xcode)

Long time reader, first time poster. I have searched all over for a solution but I am yet to find an answer that works.

Ok the problem: I have a UILabel which gets text dynamically assigned to it. If I resize the label to cover the entire view controller the text is stuck in the middle. I found a bunch of solutions which say to add the following code:

detailsLabel.numberOfLines = 0;
detailsLabel.sizeToFit()

However this doesn't do anything.

Can someone have a look at my code and provide suggestions?

import UIKit

class DetailsViewController: UIViewController {

@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var lbldetails: UILabel!


var selectedBeach : Beach?


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    detailsLabel.text = selectedBeach?.greaterDetails
    lbldetails.text = (selectedBeach?.beachName ?? "") + " Details"

    detailsLabel.numberOfLines = 0;
    [detailsLabel .sizeToFit()]

}

@IBAction func dismiss(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

ok. do the following:

  1. drag LEFT from the label to the view, release and choose Leading Space to Container Margin
  2. drag RIGHT from the label to the view, release and choose Trailing Space to Container Margin
  3. drag UPWARDS from the label to the view, release and choose Top Space to Top Layout Guide

after that go to the label's size inspector and make sure that the constraints all have a constant of Standard .

last but not least go to the label's attributes inspector and make sure that the Lines property is set to 0.

feel free to ask if you have any questions :)

The correct code in Swift is

detailsLabel.sizeToFit()

Without the [ ]

And for the Objective-C it's

[detailsLabel sizeToFit];

You can do the following things to enable UILabel that support multiline.

 lbldetails.numberOfLines = 0
 lbldetails.preferredMaxLayoutWidth = lbldetails.frame.size.width

Here i am consider that your UILable support dynamic height as per its text just issue regarding not displaying multiline.

Kindly give following constraints to UILabel . 在此处输入图片说明

Hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM