Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Lines in UILabel not showing full text

In my code (Swift 2.0 iOS 9), I've created a UIScrollView and have added a UILabel to the ScrollView to show a large set of text. The text is loaded through viewDidLoad() and is loaded from a file in the bundle.

I have used numberOfLines = 0 and label.lineBreakMode = .ByWordWrapping but only 8 lines of text show. Below the code, you will see a image of the result of the code. I have given color to the UILabel and UIScrollView to show their bounds.

override func viewDidLoad() {
    super.viewDidLoad()
    self.configureView()
    let sv = UIScrollView(frame: self.view.bounds)
    sv.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    self.view.addSubview(sv)
    sv.backgroundColor = UIColor.greenColor()
    var y: CGFloat = 10
    let file = detailItem as! String
    if let sectionsFile = NSBundle.mainBundle().pathForResource(file, ofType: "txt") {
        if let sectionText = try? String(contentsOfFile: sectionsFile, usedEncoding: nil) {
            let label = UILabel()
            label.numberOfLines = 0
            label.text = sectionText
            label.sizeToFit()
            label.frame.origin = CGPointMake(10,y)
            sv.addSubview(label)
            y += label.bounds.size.height + 10
            label.lineBreakMode = .ByWordWrapping
            label.frame.size.width = self.view.bounds.size.width - 20
            label.backgroundColor = UIColor.yellowColor()
            label.autoresizingMask = .FlexibleWidth
        }
        var sz = sv.bounds.size
        sz.height = y
        sv.contentSize = sz
    }
}

This is the results of the code: http://i.stack.imgur.com/Zh4En.png

What do I need to do to allow all of the text to show? Alternatively, is there a better way to accomplish the same goal of presenting informational text?

like image 850
AFW Avatar asked Oct 19 '22 03:10

AFW


1 Answers

Looking at your code, you are calling sizeToFit to make the label size itself, but few lines down you set width of your label's frame to a certain value, while the height stays the same. The new width is likely smaller than the one label gives itself during sizeToFit call, and that's the reason some of your text didin't fit.

Try this:

let desiredLabelWidth = self.view.bounds.size.width - 20
let size = label.sizeThatFits(CGSize(desiredLabelWidth, CGFloat.max))
label.frame = CGRect(x: 10, y: y, width: desiredLabelWidth, height: size.height)

This asks the label for it's size with a given width, and then sets the frame accordingly.

Also in your code having autoresizing mask label.autoresizingMask = .FlexibleWidth doesn't make sense because the width will change together with the superview, but the height will not, so the new size of your label will not match the text it has.

like image 187
hybridcattt Avatar answered Oct 21 '22 00:10

hybridcattt