我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。
我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?
当前回答
到目前为止,我找到的最佳解决方案是分类。这就是我如何在左右两侧添加5点填充:
@implementation UITextField (Padding)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 5, bounds.origin.y,
bounds.size.width - 10, bounds.size.height);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
#pragma clang diagnostic pop
@end
#pragma’s只是用来删除恼人的警告
其他回答
Swift 3解决方案
class CustomTextField: UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y + 8, width: bounds.size.width - 20, height: bounds.size.height - 16)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}
布洛迪的方法对我很有效。我不得不在文本框上添加侧视图,并添加额外的填充。因此,通过实现自定义UIEdgeInsets属性到UITextField子类,我已经成功实现了任务。我将在所有项目中使用这个新子类。
基于Evil Trout的回答,你可能想要创建一个类别,使它更容易在多个应用程序中使用。
头文件:
@interface UITextField (PaddingText)
-(void) setLeftPadding:(int) paddingValue;
-(void) setRightPadding:(int) paddingValue;
@end
实现文件:
#import "UITextField+PaddingText.h"
@implementation UITextField (PaddingText)
-(void) setLeftPadding:(int) paddingValue
{
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
self.leftView = paddingView;
self.leftViewMode = UITextFieldViewModeAlways;
}
-(void) setRightPadding:(int) paddingValue
{
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
self.rightView = paddingView;
self.rightViewMode = UITextFieldViewModeAlways;
}
@end
使用的例子
#import "UITextField+PaddingText.h"
[self.YourTextField setLeftPadding:20.0f];
希望这对你们有所帮助
干杯
textField.layer.borderWidth = 3;
将添加边框,这对我来说是填充。
就像这样子类UITextField (Swift版本):
import UIKit
class CustomTextField: UITextField {
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds, 25.0, 0)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return self.textRectForBounds(bounds)
}
}
这增加了25.0点的水平填充两边。