Skip to content

Instantly share code, notes, and snippets.

@BlueMilkApps
Created December 4, 2014 21:26
Show Gist options
  • Save BlueMilkApps/9b000f49a7f2aa4de7f0 to your computer and use it in GitHub Desktop.
Save BlueMilkApps/9b000f49a7f2aa4de7f0 to your computer and use it in GitHub Desktop.
import UIKit
@IBDesignable
class SomeLiveClass: UIView {
@IBInspectable var placeholder: String = "Default"
@IBInspectable var fontSize: CGFloat = 20
@IBInspectable var lineWidth: CGFloat = 1
@IBInspectable var lineColor: UIColor = UIColor.blackColor()
var textField: UITextField!
var underline: CAShapeLayer!
}
// MARK: - Lifecycle
extension SomeLiveClass {
override func awakeFromNib() {
super.awakeFromNib()
createSubviews()
}
func createSubviews() {
// Initialize text field
textField = UITextField()
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
textField.borderStyle = UITextBorderStyle.None
textField.backgroundColor = UIColor.lightGrayColor()
textField.placeholder = placeholder
textField.font = UIFont.systemFontOfSize(fontSize)
textField.sizeToFit()
addSubview(textField)
// Deal with Auto Layout
let views: [NSObject: AnyObject] = ["textField": textField]
let metrics: [NSObject: AnyObject] = ["lineWidth": lineWidth]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[textField]|", options: nil, metrics: metrics, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[textField]-(lineWidth)-|", options: nil, metrics: metrics, views: views))
}
override func layoutSubviews() {
super.layoutSubviews()
// Initialize underline
if underline != nil {
underline.removeFromSuperlayer()
}
underline = CAShapeLayer()
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(0, textField.bounds.height + (lineWidth / 2)))
bezierPath.addLineToPoint(CGPointMake(bounds.width, textField.bounds.height + (lineWidth / 2)))
underline.path = bezierPath.CGPath
underline.strokeColor = lineColor.CGColor
underline.lineWidth = lineWidth
layer.addSublayer(underline)
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: textField.bounds.height + lineWidth)
}
override func prepareForInterfaceBuilder() {
createSubviews()
}
}
// MARK: - Methods
extension SomeLiveClass {
}
// MARK: - Delegate Methods
extension SomeLiveClass {
}
// MARK: - Actions
extension SomeLiveClass {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment