How can i customise my textfield like this
-
1Please better explain your question and improve your post presentation. (punctuation matters) – technico Aug 06 '16 at 05:11
-
I would suggest use of extrnsions as an elegant syntac way Swift use to make effect to all objects of the same class within a project. – tosha Aug 06 '16 at 05:48
-
could you please elaborate... – joec Aug 06 '16 at 05:51
3 Answers
Answer for this question contains two parts. First one i related to the part of question "How to put it in a sigle file". To do this you can make a class:
class MyTextFiled: UITextField {
override func awakeFromNib() {
super.awakeFromNib()
// additional code to make UITextField looking according to your needs
//placeholder
self.text = "Placeholder"
self.textColor = UIColor.lightGrayColor()
// bottom line instead of border
}
and than click on the TextField in Interface builder and use Identity inspector to set Custom Class to MyTextField. Now you will see in run time that TextField is presented as defined in the class.
Second part is related to look of border. You have few answers here on stackoverflow covering that topic and it is all about drawing on self.layer. For example: UITextField Only Top And Bottom Border
Take a look to Text View (UITextView) Placeholder Swift too...
You can do this in a lot of ways.
First, you can subclass UITextField
and use the subclass all the time:
@IBDesignable
class CustomTextField: UITextField {
override func drawRect(rect: CGRect) {
super.drawRect(rect)
// do your custom drawing here...
}
}
override func awakeFromNib() {
super.awakeFromNib()
// initialize properties here...
}
However, if you don't need to draw custom stuff, you can try playing around with appearance()
. For example, put this in applicationDidFinishLaunchingWithOptions
and it will set all text field's background color to blue:
UITextField.appearance().backgroundColor = UIColor.blueColor()
Just by looking at the screenshot you provided, it is unclear how exactly you want your text field to look like. Is the white padding around the placeholder text a part of the text field? Is the grey border also a part of the text field? It is very unclear. But I think the first method is probably more suitable in this situation.
P.S. Your text field looks material, maybe you can try out the text field view in MaterialKit.

- 213,210
- 22
- 193
- 313
import UIKit
class MyTextField: UITextField {
override func drawRect(rect: CGRect) {
let startingPoint = CGPoint(x: rect.minX, y: rect.maxY)
let endingPoint = CGPoint(x: rect.maxX, y: rect.maxY)
let path = UIBezierPath()
path.moveToPoint(startingPoint)
path.addLineToPoint(endingPoint)
path.lineWidth = 3.0
tintColor.setStroke()
path.stroke()
}
}