-
Notifications
You must be signed in to change notification settings - Fork 0
/
DesignableUITextField.swift
97 lines (85 loc) · 3.01 KB
/
DesignableUITextField.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// File.swift
// GagaNow
//
// Created by Federico Gentile on 11/01/17.
// Copyright © 2017 Federico Gentile. All rights reserved.
//
import UIKit
@IBDesignable
public class DesignableUITextField: UITextField {
// Provides left padding for images
override public func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
override public func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.rightViewRect(forBounds: bounds)
textRect.origin.x -= rightPadding
return textRect
}
@IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
@IBInspectable var rightImage: UIImage? {
didSet {
updateView()
}
}
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var rightPadding: CGFloat = 0
@IBInspectable var color: UIColor = UIColor.lightGray {
didSet {
updateView()
}
}
@IBInspectable var borderColor: UIColor = UIColor.lightGray {
didSet {
self.layer.borderWidth = 1
self.borderStyle = .none
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderCornerRadius: CGFloat = 4 {
didSet {
self.layer.borderWidth = 1
self.borderStyle = .none
self.layer.cornerRadius = borderCornerRadius
}
}
@IBInspectable var textPadding: CGFloat = 0 {
didSet {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: textPadding, height: self.frame.height))
self.leftView = paddingView
self.leftViewMode = .always
}
}
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
}
if let image = rightImage {
rightViewMode = UITextFieldViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = image
imageView.tintColor = color
rightView = imageView
} else {
rightViewMode = UITextFieldViewMode.never
rightView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSForegroundColorAttributeName: color])
}
}