Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inset text in UILabel from left

Tags:

ios

uilabel

swift

I have a UILabel which I am using to display multiple lines of text. At the moment when the text is displayed, it is right up against the left hand side of the label which doesn't look too great. I would like the text to be inset slightly from the left.

This is my code so far:

        if notes.objectAtIndex(indexPath.row) as NSString == "" {
            cell.notesLabel.text = "No notes to display."
            cell.notesLabel.textAlignment = NSTextAlignment.Center
        } else {
            cell.notesLabel.textAlignment = NSTextAlignment.Left
        }

I was looking at some Objective-C examples but I couldn't get them to work and I don't really think they were what I was looking for.

Also, I was trying to do the same thing with a different label and in that case I assumed I could have just added " " to the end of the string (as it is a single line label) to move it in from the right, but I was surprised to see that this doesn't work?

Thanks.

like image 743
user3746428 Avatar asked Oct 12 '14 22:10

user3746428


1 Answers

To inset the text from the left edge, you should create a UILabel subclass, and override drawTextInRect:,

class RDLabel: UILabel {

    override func drawTextInRect(rect: CGRect) {
        let newRect = CGRectOffset(rect, 10, 0) // move text 10 points to the right
        super.drawTextInRect(newRect)
    }
}
like image 87
rdelmar Avatar answered Sep 27 '22 19:09

rdelmar