Skip to content

Instantly share code, notes, and snippets.

@mteera
Last active January 13, 2020 02:45
Show Gist options
  • Save mteera/a622ddca9994021da2087e2fb09c5010 to your computer and use it in GitHub Desktop.
Save mteera/a622ddca9994021da2087e2fb09c5010 to your computer and use it in GitHub Desktop.
Custom UITextField using @IBDesignable with Swift 3
import UIKit
@IBDesignable class CustomUITextField: UITextField {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
}
}
@IBInspectable var placeHolderSize: UIFont? {
get {
return self.placeHolderSize
}
set {
self.attributedPlaceholder = NSMutableAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes:[NSFontAttributeName:UIFont(name: "", size: 0)!])
}
}
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
@IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var color: UIColor = UIColor.lightGray {
didSet {
updateView()
}
}
func updateView() {
if let image = leftImage {
leftViewMode = UITextFieldViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = image
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = color
leftView = imageView
} else {
leftViewMode = UITextFieldViewMode.never
leftView = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment