我想在UITextField的开头添加空格。我使用以下代码将我的UITextfield子类化。我不确定这里出了什么问题
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 15, bounds.origin.y + 15, bounds.size.width, bounds.size.height);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 15, bounds.origin.y + 15, bounds.size.width, bounds.size.height);
}
先谢谢
答案 0 :(得分:1)
试试这个
UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(10,0,7,26)];
leftView.backgroundColor = [UIColor clearColor];
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
答案 1 :(得分:0)
您应该像这样覆盖textRectForBounds
和editingRectForBounds
:
CustomTextField.h:
#import <UIKit/UIKit.h>
@interface CustomTextField : UITextField
@property CGFloat inset;
@end
CustomTextField.m:
#import "CustomTextField.h"
@implementation CustomTextField
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, _inset, 0);
return rect;
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, _inset, 0);
return rect;
}
@end
ViewController.m:
#import "ViewController.h"
#import "CustomTextField.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet CustomTextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_textField.inset = 20;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
结果: