Skip to content

Instantly share code, notes, and snippets.

@codetalks-new
Last active August 29, 2015 14:12
Show Gist options
  • Save codetalks-new/eb3b5afe76edca001028 to your computer and use it in GitHub Desktop.
Save codetalks-new/eb3b5afe76edca001028 to your computer and use it in GitHub Desktop.
UILabel like androids TextView with drawable Left
import UIKit
class IconLabel:UIView{
var iconPadding: CGFloat = 6 {
didSet{
updateConstraintsIfNeeded()
}
}
var text :String?{
didSet{
labelView.text = text
updateFrame()
}
}
var icon :UIImage?{
didSet{
imageView.image = icon
updateFrame()
}
}
var labelView:UILabel = UILabel()
var imageView:UIImageView = UIImageView()
func commonInit(){
self.setTranslatesAutoresizingMaskIntoConstraints(false)
backgroundColor = UIColor.grayColor()
addSubview(imageView)
addSubview(labelView)
labelView.setTranslatesAutoresizingMaskIntoConstraints(false)
labelView.backgroundColor = UIColor.brownColor()
labelView.font = UIFont.systemFontOfSize(16)
labelView.text = text
imageView.contentMode = .ScaleAspectFit
imageView.backgroundColor = UIColor.cyanColor()
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
addConstraints()
}
override init() {
super.init()
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func updateFrame(){
invalidateIntrinsicContentSize()
frame.size = intrinsicContentSize()
layoutIfNeeded()
}
func addConstraints() {
let views:NSDictionary = ["icon":self.imageView,"label":self.labelView]
let metrics:NSDictionary = ["iconPadding":iconPadding]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[icon]-(>=iconPadding)-[label]|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: metrics, views: views))
addConstraint(NSLayoutConstraint(item: labelView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
}
override func intrinsicContentSize() -> CGSize {
if let ic = icon{
let icSize = ic.size
let labelSize = labelView.intrinsicContentSize()
let width = icSize.width + iconPadding + labelSize.width
let height = max(icSize.height, labelSize.height)
return CGSize(width: width, height: height)
}else{
return labelView.intrinsicContentSize()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment