Learn to create a stunning textfield with icon in Swift
As our apps get aesthetically more appealing, there is an even greater demand to enhance every possible UI element in the mobile app.
Picture speaks a thousand words, and icons educate users how to navigate in the mobile world, connecting images to actions.
So in this short tutorial, I will bring you through my most preferred way to inculcate an icon in UITextField
.
Step 1: Add a basic UITextField
and give it basic constraints:
Step 2: Connect the UITextField
to its ViewController's IBOutlet:
@IBOutlet weak var iconTextField: UITextField!
Step 3: Add Icon to Assets.xcassets
and set Render As
to Template Image:
I got this user icon from https://icons8.com/icon/set/user/ios.
Step 4: Extend UITextField
and create a new setIcon
function:
Ever since Swift’s evolution of making extensions widely available to us, it makes customisation of UI elements much simpler. Go ahead and create a function call setIcon
that look like this:
extension UITextField {func setIcon(_ image: UIImage) { let iconView = UIImageView(frame:
CGRect(x: 10, y: 5, width: 20, height: 20))
iconView.image = image let iconContainerView: UIView = UIView(frame:
CGRect(x: 20, y: 0, width: 30, height: 30))
iconContainerView.addSubview(iconView) leftView = iconContainerView
leftViewMode = .always}}
So here we create an iconView
, the size of the icon, giving a padding of about 10px, center align with 5px.
Then we create an iconContainerView
so that there is a small padding between the icon and the main textfield itself. Finally we add the iconView
as a subview in iconContainerView
and set it to leftView
, enabling leftViewMode
to .always
will allow the TextField
to always show the icon.
Step 5: Set the icon and apply tint color!
@IBOutlet weak var iconTextField: UITextField! {
didSet {
iconTextField.tintColor = UIColor.lightGray
iconTextField.setIcon(imageLiteral(resourceName: "icon-user"))
}
}
If you are wondering whats imageLiteral(resourceName: "icon-user")
this is a new Xcode’s functionality where it allows you to use image asset’s name in replacement of UIImage(named: "icon-user")
. This allows you to view the image resource in real-time on the editor itself. Thank you Xcode!
So with this, try running and you should get your gorgeous-looking UITextField
with Icon!
Final Words
There are many other methods out there that can get this working, you could create @IBDesignable
, create a Custom Class
etc. Feel free to explore from here if its your first time adding image to textfield, or drop comments to suggest better methods. Thank you for reading and have fun coding!