Created
April 4, 2019 21:21
-
-
Save aniltv06/d714e350da088dc6d12eb0dda5a12340 to your computer and use it in GitHub Desktop.
Textfield with image placeholder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| @IBDesignable | |
| class DesignableUITextField: UITextField { | |
| // Provides left padding for images | |
| 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 = UITextField.ViewMode.always | |
| let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) | |
| imageView.contentMode = .scaleAspectFit | |
| 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 = UITextField.ViewMode.never | |
| leftView = nil | |
| } | |
| // Placeholder text color | |
| attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: color]) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment