Reputation: 690
I have created an image for textfield in my iOS app. But the text seems to overlap the image. Is there any way to prevent this or achieve the same design in another way. Below is the image of the problem I'm facing.
Is there any way to make the text start from a particular position in the text field?
Upvotes: 2
Views: 1947
Reputation: 690
I did also find another way to achieve this by adding offset to the textfield. But found out this would not be an ideal solution when you have multiple text fields in the same view. Just adding the solution as a reference to others so that someone finds it helpful.
let paddingView = UIView(frame: CGRectMake(0, 0, 60, self.yourTextField.frame.height))
yourTextField.leftView = paddingView
yourTextField.leftViewMode = UITextFieldViewMode.Always
Upvotes: 0
Reputation: 39081
This will allow you to change the rect where the text will go:
class MyCustomTextField : UITextField {
var leftMargin : CGFloat = 10.0
override func textRectForBounds(bounds: CGRect) -> CGRect {
var newBounds = bounds
newBounds.origin.x += leftMargin
return newBounds
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
var newBounds = bounds
newBounds.origin.x += leftMargin
return newBounds
}
}
Upvotes: 1
Reputation: 534893
One solution is to make your UITextField a subclass of UITextField. This will allow you to override textRectForBounds:
- and now you are in charge of where the text will go.
In particular, in your override, call super
to get the original rect. Now increase the x-component of the origin by some amount to allow room for your image, and decrease the width of the size by that same amount. Return the resulting modified rect and you're done.
Upvotes: 2