Skip to content

Instantly share code, notes, and snippets.

@Sjahriyar
Created December 19, 2019 09:39
Show Gist options
  • Save Sjahriyar/52e0e5144476be8aac1be9919415a6c8 to your computer and use it in GitHub Desktop.
Save Sjahriyar/52e0e5144476be8aac1be9919415a6c8 to your computer and use it in GitHub Desktop.
Custom UITextField with padding
//
// CustomTextField.swift
//
// Created by Shahriyar Soheilizadeh on 18/12/2019.
// Copyright © 2019 Shahriyar Soheilizadeh. All rights reserved.
//
import UIKit
class CustomTextField: UITextField
{
private var padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
@IBInspectable public var bottomInset: CGFloat {
get { return padding.bottom }
set { padding.bottom = newValue }
}
@IBInspectable public var leftInset: CGFloat {
get { return padding.left }
set { padding.left = newValue }
}
@IBInspectable public var rightInset: CGFloat {
get { return padding.right }
set { padding.right = newValue }
}
@IBInspectable public var topInset: CGFloat {
get { return padding.top }
set { padding.top = newValue }
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: self.padding)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: self.padding)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: self.padding)
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
if let right = rightView {
return CGRect(origin: CGPoint(x: (self.bounds.maxX - right.frame.size.width) - self.padding.right, y: self.bounds.midY - right.frame.size.height / 2), size: right.frame.size)
}
return .zero
}
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
if let left = leftView {
return CGRect(origin: CGPoint(x: (self.bounds.maxX - left.frame.size.width) - self.padding.left, y: self.bounds.midY - left.frame.size.height / 2), size: left.frame.size)
}
return .zero
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment