Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel vertical alignment

Tags:

ios

uilabel

swift

In my application i am using ActiveLabelfram Github.

In that case, my label does not show the text in the middle of the UILabel. If i use a normal UILabel it works fine, but when settings it to a ActiveLabel, it gets like this. enter image description here

(Image is taken in runtime)

I think this is the code to play with the alignment somehow:

/// add line break mode
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
    let mutAttrString = NSMutableAttributedString(attributedString: attrString)

    var range = NSRange(location: 0, length: 0)
    var attributes = mutAttrString.attributesAtIndex(0, effectiveRange: &range)

    let paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
    if let lineSpacing = lineSpacing {
        paragraphStyle.lineSpacing = CGFloat(lineSpacing)
    }

    attributes[NSParagraphStyleAttributeName] = paragraphStyle
    mutAttrString.setAttributes(attributes, range: range)

    return mutAttrString
}

ActiveLabel.swift

ActiveType.swift

Any ideas how i can make it in the middle like this: enter image description here

(Image is taken from Storyboard)

like image 974
Roduck Nickes Avatar asked Dec 16 '15 01:12

Roduck Nickes


People also ask

What is UILabel?

A view that displays one or more lines of informational text.

How do I center text in a label in HTML?

One way to center text or put it in the middle of the page is to enclose it within <center></center> tags. Inserting this text within HTML code would yield the following result: Center this text!

How do I center a label in Xcode?

click on Align button on bottom toolbar in IB then select Horizontal or Vertical center. First you might want to fix width and height as well, if you want to preserve size. Save this answer.


1 Answers

In ActiveLabel.swift replace the drawTextInRect method with

public override func drawTextInRect(rect: CGRect) {
        let range = NSRange(location: 0, length: textStorage.length)

        textContainer.size = rect.size

        let usedRect = layoutManager.usedRectForTextContainer(textContainer)

        let glyphOriginY = (rect.height > usedRect.height) ? rect.origin.y + (rect.height - usedRect.height) / 2 : rect.origin.y
        let glyphOrigin = CGPointMake(rect.origin.x, glyphOriginY)

        layoutManager.drawBackgroundForGlyphRange(range, atPoint: glyphOrigin)
        layoutManager.drawGlyphsForGlyphRange(range, atPoint: glyphOrigin)
    }

I have also forked the repo under https://github.com/rishi420/ActiveLabel.swift

If you download the repo, remember to set verticalTextAlignmentCenter to true

like image 56
Warif Akhand Rishi Avatar answered Sep 18 '22 15:09

Warif Akhand Rishi