I have a textfield with some placeholder. I want to give the margin of 20PX from left to show the placeholder and also wants to set initial cutsor at same margin.
Asked
Active
Viewed 1,229 times
1
-
http://stackoverflow.com/questions/5674655/add-lefthand-margin-to-uitextfield – user3182143 Jul 21 '16 at 09:16
4 Answers
6
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

pkamb
- 33,281
- 23
- 160
- 191

martinsaha
- 63
- 6
3
You have to create a subclass of UITextField
and override the textRectForBounds:
and editingRectForBounds:
methods to return an insetted rect.
You could do something similar to:
func textRectForBounds(bounds: CGRect) -> CGRect {
return adjustBounds(bounds)
}
func editingRectForBounds(bounds: CGRect) -> CGRect {
return adjustBounds(bounds)
}
private func adjustBounds(bounds: CGRect) -> CGRect {
var newBounds = bounds
newBounds.origin.x += 20
newBounds.size.width -= 20
return newBounds
}
// If you need to place the UITextField placeholder in the initial 20px,
// you have to override this method as well to provide the right rect.
func placeholderRect(forBounds bounds: CGRect) -> CGRect {
var newBounds = bounds
newBounds.origin.x = 0
newBounds.size.width = 20
return newBounds
}
Reference: Text inset for UITextField?

Community
- 1
- 1

Alessandro Orrù
- 3,443
- 20
- 24
1
You can create a custom UITextField. Implement following methods and set Inset value as required
// placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 10, 10);
}
// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 10, 0);
}

Saraswati
- 1,516
- 1
- 14
- 21
1
For placeholder position:
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset( self.bounds , margin position , margin position );
}
For text position:
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectInset( self.bounds , margin position ,margin position );
}

pkamb
- 33,281
- 23
- 160
- 191

Suraj Sukale
- 1,778
- 1
- 12
- 19