Last active
May 9, 2019 03:12
-
-
Save enomoto/e64160b29083c5feaa20cb1bc0d331af to your computer and use it in GitHub Desktop.
UILabel with rounded corners (Swift 5, Xcode 10.2)
This file contains hidden or 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
@IBDesignable | |
public final class RoundedCornersLabel: UILabel { | |
public override init(frame: CGRect) { | |
super.init(frame: frame) | |
configure() | |
} | |
public required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
configure() | |
} | |
public override func prepareForInterfaceBuilder() { | |
super.prepareForInterfaceBuilder() | |
configure() | |
} | |
public override var text: String? { | |
didSet { | |
if let text = text { | |
calculateFrameRect(with: text) | |
} | |
} | |
} | |
private func configure() { | |
font = .systemFont(ofSize: 10) | |
textColor = .lightGray | |
textAlignment = .center | |
numberOfLines = 1 | |
layer.cornerRadius = 10 | |
layer.borderWidth = 0.7 | |
layer.borderColor = UIColor.lightGray.cgColor | |
calculateFrameRect(with: text) | |
} | |
private func calculateFrameRect(with text: String?) { | |
guard let text = text else { return } | |
let width: CGFloat = { | |
let dummyLabel = UILabel() | |
dummyLabel.text = text | |
dummyLabel.font = font | |
dummyLabel.sizeToFit() | |
return dummyLabel.frame.width + 20 | |
}() | |
frame = CGRect(x: frame.minX, | |
y: frame.minY, | |
width: width, | |
height: frame.height) | |
// Remove an old constraint when text was set | |
calculatedWidthAnchor?.isActive = false | |
calculatedWidthAnchor = widthAnchor.constraint(equalToConstant: width) | |
calculatedWidthAnchor?.isActive = true | |
} | |
var calculatedWidthAnchor: NSLayoutConstraint? | |
} | |
extension RoundedCornersLabel { | |
@IBInspectable var cornerRadius: CGFloat { | |
get { | |
return layer.cornerRadius | |
} | |
set { | |
layer.cornerRadius = newValue | |
layer.masksToBounds = newValue > 0 | |
} | |
} | |
@IBInspectable | |
var borderWidth: CGFloat { | |
get { | |
return self.layer.borderWidth | |
} | |
set { | |
self.layer.borderWidth = newValue | |
} | |
} | |
@IBInspectable | |
var borderColor: UIColor? { | |
get { | |
return UIColor(cgColor: self.layer.borderColor!) | |
} | |
set { | |
self.layer.borderColor = newValue?.cgColor | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment