我正在以编程方式将UITextField添加到tableViewCell中,当前光标正好在textField的左侧启动。我使用xib文件添加的textField在这里总是有差距。
有谁知道如何手动应用此差距?
这是我的textField:
这就是我希望textField的样子:
预期尺寸,字体,颜色或UITextField是否有任何细节?
我认为高度应该是31但是我不确定我应该设置哪些其他特性来使我的自定义看起来像添加的xib。
感谢您的帮助:)
编辑:
感谢您的帮助 - 查看答案,我的情况略有不同,因为我使用的是keepLayout,而不是设置一个带矩形的框架。有没有办法使用keepLayout解决这个问题,还是需要使用框架?
答案 0 :(得分:2)
按照Bellow步骤使用类别。您可以创建如下类别: -
#import <UIKit/UIKit.h>
@interface UITextField (mytextFiled)
- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;
@end
.m文件
#import "UITextField+bgImageset.h"
@implementation UITextField (mytextFiled)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 20, bounds.origin.y + 5,
bounds.size.width - 20, bounds.size.height - 10);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
@end
使用以上类别我的textfiled
看起来像吼叫我正在设置textfiled
的图像,以便看起来有点不同......
答案 1 :(得分:0)
我在最近的应用程序中实现此目的的方式是 -
usernameTextField = [[UIView alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 10.0f, 40.0f)];
usernameTextField.leftView.backgroundColor = [UIColor clearColor];
usernameTextField.leftViewMode = UITextFieldViewModeAlways;
将UITextField
扩展为所讨论的here类别并不是一个好习惯。
答案 2 :(得分:0)
这可以通过使用textField.leftView
在这里添加任何视图,即图像或空视图来完成,就像
txtField.leftViewMode = UITextFieldViewModeAlways;
txtField.leftView = imageView;
答案 3 :(得分:0)
我的答案与@ Nitin相似。但是,我没有创建一个类别,而是将UITextField
子类化为实现:
代码如下:
.h
:
#import <UIKit/UIKit.h>
@interface W3BTextField : UITextField
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
.m
:
#import "W3BTextField.h"
@implementation W3BTextField
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(6.5, 10, 6.5, 5);
}
return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
@end
现在所有这些都是以编程方式完成的,而不使用XIB
s / storyboard
s。
在这样的课程中使用:
W3BTextField* registrationFullName = [[W3BTextField alloc] initWithFrame:CGRectMake(30, 25, 260, 35)];
registrationFullName.placeholder = @"Full name";
registrationFullName.font = [UIFont fontWithName:@"HelveticaNeue" size:15];
registrationFullName.textColor = UIColorFromRGB(0x333333);
registrationFullName.layer.cornerRadius = 1.0f;
registrationFullName.backgroundColor = [UIColor whiteColor];
registrationFullName.delegate = self;
[registrationFullName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];