Last active
October 21, 2017 06:19
-
-
Save 5oya/dbe7255b610e00bf96b7218914182fe4 to your computer and use it in GitHub Desktop.
【iOS】PaddingがあるUILabel
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
import UIKit | |
final class PaddingLabel: UILabel { | |
private let height: CGFloat = 16 | |
private let contentInsets: UIEdgeInsets = { | |
let hPadding: CGFloat = 6, vPadding: CGFloat = 2 | |
let contentInsets = UIEdgeInsets(top: vPadding, left: hPadding, bottom: vPadding, right: hPadding) | |
return contentInsets | |
}() | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
textColor = .white | |
font = UIFont.boldSystemFont(ofSize: 10) | |
numberOfLines = 1 | |
layer.cornerRadius = height / 2 | |
clipsToBounds = true | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
sizeToFit() | |
} | |
override func draw(_ rect: CGRect) { | |
let insetsInsetRect = UIEdgeInsetsInsetRect(rect, contentInsets) | |
return super.drawText(in: insetsInsetRect) | |
} | |
override func sizeThatFits(_ size: CGSize) -> CGSize { | |
var contentSize = size | |
let hOffset = contentInsets.left + contentInsets.right | |
let vOffset = contentInsets.top + contentInsets.bottom | |
contentSize.width -= hOffset | |
contentSize.height -= vOffset | |
var baseSize = super.sizeThatFits(contentSize) | |
baseSize.width += hOffset | |
baseSize.height += vOffset | |
return baseSize | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment