Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// RoundedTextField.swfit
//
// Created by Maysam Shahsavari on 2020-07-30.
// Copyright © 2020 Maysam Shahsavari. All rights reserved.
//
import UIKit
/// Configuration for `RoundedTextField`
struct RoundedTextFieldConfig {
let font: UIFont?
let returnType: UIReturnKeyType
let cornerRadius: CGFloat
let borderWidth: CGFloat
let borderColor: UIColor
let placeholderText: NSAttributedString?
let cleaButtonOffset: CGFloat?
let leftSidePadding: CGFloat
let accessoryView: UIView?
}
/// A customizable `UITextField` with rounded corners
class RoundedTextField: UITextField {
private var _cleaButtonOffset: CGFloat = 0
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
let originalRect = super.clearButtonRect(forBounds: bounds)
return originalRect.offsetBy(dx: _cleaButtonOffset * -1, dy: 0)
}
func config(_ config: RoundedTextFieldConfig) {
self._cleaButtonOffset = config.cleaButtonOffset ?? 0
let sideView = UIView(frame: CGRect(x: 0, y: 0,
width: config.leftSidePadding, height: self.bounds.height))
self.font = config.font
self.leftView = sideView
self.leftViewMode = .always
self.inputAccessoryView = config.accessoryView
self.clearButtonMode = .whileEditing
self.returnKeyType = config.returnType
self.clipsToBounds = true
self.layer.masksToBounds = true
self.layer.cornerRadius = self.bounds.height / 2
self.layer.borderWidth = 5
self.layer.borderColor = config.borderColor.cgColor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment