Created
March 23, 2016 07:20
-
-
Save karthikgs7/a5d8176eddcef430b617 to your computer and use it in GitHub Desktop.
Auto resizing label in Swift with Auto Layout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// AutoResizingLabel.swift | |
// | |
// Created by karthikeyan on 3/23/16. | |
// Copyright © 2016 karthikeyan All rights reserved. | |
// | |
import Foundation | |
import UIKit | |
class AutoResizingLabel: UIView { | |
//MARK:- Private instance variables | |
private var label: UILabel! | |
//MARK:- Public instance variables | |
var font: UIFont = UIFont.systemFontOfSize(18) { | |
didSet { | |
label.font = font | |
} | |
} | |
var text: String = "Sample text" { | |
didSet { | |
label.text = text | |
} | |
} | |
//MARK:- Life cycle methods | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
setupView() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
setupView() | |
} | |
//MARK:- Private helper methods | |
private func setupView() { | |
setupLabel() | |
setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) | |
setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Vertical) | |
setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal) | |
setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Vertical) | |
label.backgroundColor = .clearColor() | |
} | |
private func setupLabel() { | |
label = UILabel() | |
label.text = text | |
label.numberOfLines = 0 | |
label.textAlignment = .Center | |
label.translatesAutoresizingMaskIntoConstraints = false | |
addSubview(label) | |
label.centerXAnchor.constraintEqualToAnchor(centerXAnchor).active = true | |
label.centerYAnchor.constraintEqualToAnchor(centerYAnchor).active = true | |
label.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) | |
label.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Vertical) | |
label.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal) | |
label.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Vertical) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment