Skip to content

Instantly share code, notes, and snippets.

@angelinaFri
Forked from soggybag/CustomTextField.swift
Created January 16, 2021 11:47
Show Gist options
  • Save angelinaFri/d02172308596e1154a244b4355854051 to your computer and use it in GitHub Desktop.
Save angelinaFri/d02172308596e1154a244b4355854051 to your computer and use it in GitHub Desktop.
Adds border, corner radius, and padding to the UITextField. These properties can be set via the attribute inspector in storyboard.
import UIKit
@IBDesignable
class CustomTextField: UITextField {
var padding: UIEdgeInsets {
get {
return UIEdgeInsets(top: 0, left: paddingValue, bottom: 0, right: paddingValue)
}
}
override func textRectForBounds(bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
@IBInspectable var paddingValue: CGFloat = 0
@IBInspectable var borderColor: UIColor? = UIColor.clearColor() {
didSet {
layer.borderColor = self.borderColor?.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = self.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = self.cornerRadius
layer.masksToBounds = self.cornerRadius > 0
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func drawRect(rect: CGRect) {
self.layer.cornerRadius = self.cornerRadius
self.layer.borderWidth = self.borderWidth
self.layer.borderColor = self.borderColor?.CGColor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment