UITextfiled的leftView属性在Objective-C中不起作用

时间:2019-04-30 05:43:39

标签: ios objective-c uitextfield

textSearchField.hidden = NO;
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 50, 20)];
textSearchField.leftView = paddingView;
textSearchField.leftViewMode = UITextFieldViewModeAlways;
[search_view addSubview:textSearchField];

我想使用UITextfieldObjective-C添加左填充-10像素。如果还有其他解决方案?

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码以编程方式创建

CGRect someRect = CGRectMake(0.0, 0.0, 100.0, 30.0);
DKTextField* textField = [[DKTextField alloc] initWithFrame:someRect];
textField.padding = 1.0
[self.view addSubview:textField];

使用以下类

DKTextField.h

#import <UIKit/UIKit.h>

@interface DKTextField : UITextField

@property (nonatomic) IBInspectable CGFloat padding;

@end

DKTextField.m

#import "DKTextField.h"

IB_DESIGNABLE
@implementation DKTextField

@synthesize padding;

-(CGRect)textRectForBounds:(CGRect)bounds{
    return CGRectInset(bounds, padding, padding);
}

-(CGRect)editingRectForBounds:(CGRect)bounds{
    return [self textRectForBounds:bounds];
}

@end

您只需将所选的UITextField分配给DKTextField

无论您想要什么填充,都可以像下面的图片一样添加它。

答案 1 :(得分:0)

//尝试一下

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.placeholder = @"enter text";
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:textField];

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 50, 20)];
paddingView.backgroundColor = [UIColor darkGrayColor];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

检查图像

enter image description here