Reputation: 4506
I'm already setting the LeftView of my UITextField so that I can draw a little icon next to the text.
Password.LeftView = new UIImageView(UIImage.FromBundle("LockAndKey"));
Password.LeftViewMode = UITextFieldViewMode.Always;
This works great but the problem now is that the placeholder and actual text is too close to the image - I'd like to indent over the text.
What do I need to do in Xamarin/iOS for my subclassed UITextField to indent the text with a margin? I know there are various functions I can override but haven't had success with it for the text so far.
Thanks!
Upvotes: 4
Views: 2094
Reputation: 9346
You need to extend/subclass the UITextField class and override the method called DrawText
. There you add the padding you need.
public override void DrawText(CGRect rect)
{
var padding = new UIEdgeInsets (0, 10, 0, 0);
base.DrawText( padding.InsetRect(rect));
}
This will add a 10 points padding to the left.
To make it more customizable I'd add a property called Padding where basically you can set the padding you need depending on the situation.
* UPDATE #1 *
In the case you want to have the space while typing you can just make the UIImageView that represent your LeftView a little bigger in width and play with the ViewContentMode
Using your example:
var leftView = new UIImageView(UIImage.FromBundle("LockAndKey"));
leftView.Frame = new CGRect (leftView.Frame.X, leftView.Frame.Y, leftView.Frame.Width + 15, leftView.Frame.Height);
leftView.ContentMode = UIViewContentMode.Center;
Password.LeftView = leftView
Password.LeftViewMode = UITextFieldViewMode.Always;
With this configuration you will have 7.5 points on each size of the ImageView. You can use others ContentMode to make it work as you'd like.
**** UPDATE #2 ****
Just found another way.
In your subclass UITextField override these two methods:
public override CGRect TextRect (CGRect forBounds)
{
var padding = new UIEdgeInsets (0, 20, 0, 0);
return base.TextRect (padding.InsetRect(forBounds));
}
public override CGRect EditingRect (CGRect forBounds)
{
return TextRect (forBounds);
}
This one is cleaner and as the first solution you can customize it.
Upvotes: 6