95

iOS7 上 UITextField 的 leftView 和 rightView 视图非常接近文本框的边框。

如何为这些项目添加一些(水平)填充?

我尝试修改框架,但没有工作

uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];    
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;

请注意,我对向文本字段的文本添加填充不感兴趣,例如Set padding for UITextField with UITextBorderStyleNone

4

28 回答 28

168

一个更简单的解决方案,它利用了contentMode

    arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"down_arrow"]];
    arrow.frame = CGRectMake(0.0, 0.0, arrow.image.size.width+10.0, arrow.image.size.height);
    arrow.contentMode = UIViewContentModeCenter;

    textField.rightView = arrow;
    textField.rightViewMode = UITextFieldViewModeAlways;

在 Swift 3 中,

    let arrow = UIImageView(image: UIImage(named: "arrowDrop"))
    if let size = arrow.image?.size {
        arrow.frame = CGRect(x: 0.0, y: 0.0, width: size.width + 10.0, height: size.height)
    }
    arrow.contentMode = UIViewContentMode.center
    self.textField.rightView = arrow
    self.textField.rightViewMode = UITextFieldViewMode.always
于 2014-06-24T13:53:41.410 回答
95

我自己正在研究这个并使用了这个解决方案:

- (CGRect) rightViewRectForBounds:(CGRect)bounds {

    CGRect textRect = [super rightViewRectForBounds:bounds];
    textRect.origin.x -= 10;
    return textRect;
}

这会将图像从右侧移动 10,而不是在 iOS 7 中将图像挤压到边缘。

此外,这是在 的子类中UITextField,可以通过以下方式创建:

  1. 创建一个新文件,它是的子类UITextField而不是默认文件NSObject
  2. 添加一个名为- (id)initWithCoder:(NSCoder*)coder设置图像的新方法

    - (id)initWithCoder:(NSCoder*)coder {
        self = [super initWithCoder:coder];
    
        if (self) {
    
            self.clipsToBounds = YES;
            [self setRightViewMode:UITextFieldViewModeUnlessEditing];
    
            self.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"textfield_edit_icon.png"]];
        }
    
        return self;
    }
    
  3. 您可能需要导入#import <QuartzCore/QuartzCore.h>

  4. 添加rightViewRectForBounds上面的方法

  5. 在 Interface Builder 中,单击要子类化的 TextField 并将类属性更改为这个新子类的名称

于 2013-10-15T04:10:04.300 回答
50

最简单的方法是将 UIView 添加到 leftView/righView 并将 ImageView 添加到 UIView ,在 UIView 内任意位置调整 ImageView 的原点,这对我来说就像一个魅力。它只需要几行代码

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 26, 26)];
imgView.image = [UIImage imageNamed:@"img.png"];

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
[paddingView addSubview:imgView];
[txtField setLeftViewMode:UITextFieldViewModeAlways];
[txtField setLeftView:paddingView];
于 2014-06-27T11:48:15.747 回答
15

这对 Swift 非常有用:

let imageView = UIImageView(image: UIImage(named: "image.png"))
imageView.contentMode = UIViewContentMode.Center
imageView.frame = CGRectMake(0.0, 0.0, imageView.image!.size.width + 20.0, imageView.image!.size.height)
textField.rightViewMode = UITextFieldViewMode.Always
textField.rightView = imageView
于 2015-07-31T17:08:00.977 回答
8

这对我有用

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
self.passwordTF.leftView = paddingView;
self.passwordTF.leftViewMode = UITextFieldViewModeAlways;

愿它对你有所帮助。

于 2015-08-01T04:57:14.657 回答
6

我喜欢这个解决方案,因为它用一行代码解决了问题

myTextField.layer.sublayerTransform = CATransform3DMakeTranslation(10.0f, 0.0f, 0.0f);

注意:.. 或 2 如果您考虑包含 QuartzCore 一行:)

于 2014-12-24T11:01:22.133 回答
5

斯威夫特 5

class CustomTextField: UITextField {
    func invalidate() {
        let errorImage =  UIImageView(image: UIImage(named: "errorImage"))
        errorImage.frame = CGRect(x: 8, y: 8, width: 16, height: 16)
        rightView = UIView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
        rightView?.addSubview(errorImage)
        rightViewMode = .always
    }
}

你会想要:

  • 子类UITextField
  • 在子类文本字段中编写一个无效方法
  • 在 invalidate 方法中,创建一个UIView 比你的图像更大的
  • 将您的图像放在视图内
  • 将视图分配给UITextField.rightView
于 2020-01-07T17:37:49.793 回答
5

我们可以覆盖苹果为 rightView 提供的方法,而不是操作 imageView 或 image。

class CustomTextField : UITextField { 

override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
    let offset = 5
    let width  = 20
    let height = width
    let x = Int(bounds.width) - width - offset
    let y = offset
    let rightViewBounds = CGRect(x: x, y: y, width: width, height: height)
    return rightViewBounds
}}

同样的方式,我们可以为左视图覆盖下面的 func 。

override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    /*return as per requirement*/

}
于 2019-03-07T10:40:39.120 回答
4

The best way to do this is simply make a class using subclass of UITextField and in .m file

  #import "CustomTextField.h"
  #import <QuartzCore/QuartzCore.h>
  @implementation CustomTextField


- (id)initWithCoder:(NSCoder*)coder 
 {
self = [super initWithCoder:coder];

if (self) {

    //self.clipsToBounds = YES;
    //[self setRightViewMode:UITextFieldViewModeUnlessEditing];

    self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,15,46)];
    self.leftViewMode=UITextFieldViewModeAlways;
      }

return self;

}

by doing this go to your storyboard or xib and click on identity inspector and replace UITextfield with your own "CustomTextField" in class option.

Note: If you simply give padding with auto layout for textfield then your application will not run and show only blank screen.

于 2015-03-19T08:26:48.990 回答
3

我在某个地方发现了这个...

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
paddingView.backgroundColor = [UIColor clearColor];
itemDescription.leftView = paddingView;
itemDescription.leftViewMode = UITextFieldViewModeAlways;

[self addSubview:itemDescription];
于 2013-10-14T23:45:06.753 回答
1

创建一个自定义 UITextField 类并使用该类而不是 UITextField。覆盖 - (CGRect) textRectForBounds:(CGRect)bounds 以设置您需要的矩形

例子

- (CGRect)textRectForBounds:(CGRect)bounds{
     CGRect textRect = [super textRectForBounds:bounds];
     textRect.origin.x += 10;
     textRect.size.width -= 10;
     return textRect;
}
于 2013-10-15T00:23:11.397 回答
1

这是一种解决方案:

 UIView *paddingTxtfieldView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 42)]; // what ever you want 
 txtfield.leftView = paddingTxtfieldView;
 txtfield.leftViewMode = UITextFieldViewModeAlways;
于 2013-10-15T05:32:29.627 回答
1

下面的示例用于向恰好是图标的左视图添加水平填充 - 您可以使用类似的方法将填充添加到UIView您想用作文本字段左视图的任何内容。

内部UITextField子类:

static CGFloat const kLeftViewHorizontalPadding = 10.0f;

@implementation TextFieldWithLeftIcon
{
  UIImage *_image;
  UIImageView *_imageView;
}

- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image
{
  self = [super initWithFrame:frame];
  if (self) {
    if (image) {
      _image = image;
      _imageView = [[UIImageView alloc] initWithImage:image];
      _imageView.contentMode = UIViewContentModeCenter;
      self.leftViewMode = UITextFieldViewModeAlways;
      self.leftView = _imageView;
    }
  }
  return self;
}

#pragma mark - Layout 

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
  CGFloat widthWithPadding = _image.size.width + kLeftViewHorizontalPadding * 2.0f;
  return CGRectMake(0, 0, widthWithPadding, CGRectGetHeight(bounds));
}

虽然我们在UITextField这里是一个子类,但我相信这是最干净的方法。

于 2014-12-23T00:03:00.323 回答
1

我在 ViewController 类中创建了一个自定义方法,如下所示:

- (void) modifyTextField:(UITextField *)textField
{
    // Prepare the imageView with the required image
    uint padding = 10;//padding for iOS7
    UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];    
    iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);

    // Set the imageView to the left of the given text field.
    textField.leftView = iconImageView;
    textField.leftViewMode = UITextFieldViewModeAlways;
}

viewDidLoad现在我可以在 ( method)内部调用该方法并将我的任何内容发送TextFields到该方法并为左右添加填充,并通过仅编写一行代码来提供文本和背景颜色,如下所示:

[self modifyTextField:self.firstNameTxtFld];

这在 iOS 7 上完美运行!希望这仍然适用于 iOS 8 和 9!

我知道添加太多视图可能会使加载的对象更重。但是当担心其他解决方案的困难时,我发现自己更倾向于这种方法,并且使用这种方式更灵活。;)

希望这个答案可能对其他人找出另一种解决方案有所帮助或有用。

干杯!

于 2014-03-18T05:38:40.257 回答
1
- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.size.width - 40, 0, 40, bounds.size.height);
}
于 2015-04-21T09:59:27.917 回答
1

谢谢你们的回答,令我惊讶的是,他们都没有真正为我的文本字段提供正确的视图图像,同时仍然提供所需的填充。然后我想到了使用 AspectFill 模式,奇迹发生了。对于未来的寻求者,这就是我使用的:

UIImageView *emailRightView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
emailRightView.contentMode = UIViewContentModeScaleAspectFill;
emailRightView.image = [UIImage imageNamed:@"icon_email.png"];
emailTextfield.rightViewMode = UITextFieldViewModeAlways;
emailTextfield.rightView = emailRightView;

我的 imageview 框架中的 35 代表我的 emailTextfield 的高度,请随时根据您的需要进行调整。

于 2015-05-14T19:32:07.440 回答
1

这对我有用,就像我在寻找:

func addImageViewInsideMyTextField() {
    let someView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 24))
    let imageView = UIImageView(image: UIImage(named: "accountImage"))
    imageView.frame = CGRect(x: 16, y: 0, width: 24, height: 24)
    imageView.contentMode = .scaleAspectFit
    someView.addSubview(imageView)

    self.myTextField.leftView = someView
    self.myTextField.leftViewMode = .always
}
于 2020-02-14T07:20:42.113 回答
1

我自己也遇到过这个问题,到目前为止,最简单的解决方案是修改您的图像以简单地在图像的每一侧添加填充!

我刚刚更改了我的 png 图像以添加 10 像素的透明填充,并且效果很好,根本不需要编码!

于 2015-08-13T21:11:50.773 回答
1

如果您使用 UIImageView 作为 leftView 那么您必须使用以下代码:

注意:不要在 viewWillAppear 或 viewDidAppear 中使用

-(UIView*)paddingViewWithImage:(UIImageView*)imageView andPadding:(float)padding
{
    float height = CGRectGetHeight(imageView.frame);
    float width =  CGRectGetWidth(imageView.frame) + padding;

    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];

    [paddingView addSubview:imageView];

    return paddingView;
}
于 2015-09-20T19:30:11.917 回答
1

从 iOS 13 和 Xcode 11 开始,这是唯一适合我们的解决方案。

// Init of custom UITextField
override init(frame: CGRect) {
    super.init(frame: frame)

    if let size = myButton.imageView?.image?.size {
        myButton.frame = CGRect(x:0, y: 0, width: size.width, height: size.height)

        let padding: CGFloat = 5
        let container = UIView(frame: CGRect(x:0, y: 0, width: size.width + padding, height: size.height))
        container.addSubview(myButton)

        myButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myButton.topAnchor.constraint(equalTo: container.topAnchor),
            myButton.leftAnchor.constraint(equalTo: container.leftAnchor),
            myButton.bottomAnchor.constraint(equalTo: container.bottomAnchor),
            myButton.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -padding),
        ])

        textField.rightViewMode = .always
        textField.rightView = container
    }
}
于 2020-03-17T11:03:39.867 回答
1

UITextField设置使用 swift 4.2的 Rightview

TxtPass.rightViewMode = UITextField.ViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 18, height: 18))
imageView.contentMode = UIView.ContentMode.scaleAspectFit
let image = UIImage(named: "hidepass")
imageView.image = image
let rightView = UIView(frame: CGRect(x: 0, y: 0, width: 28, height: 18))
rightView.addSubview(imageView)
rightView.contentMode = UIView.ContentMode.left
TxtPass.rightView = rightView
于 2020-05-10T10:11:55.183 回答
0

一招:将包含 UIImageView 的 UIView 作为 rightView 添加到 UITextField。这个 UIView 必须更大,现在把 UIImageView 放在它的左边。所以从右边会有一个空间填充。

// Add a UIImageView to UIView and now this UIView to UITextField - txtFieldDate
UIView *viewRightIntxtFieldDate = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 30)]; 
// (Height of UITextField is 30px so height of viewRightIntxtFieldDate = 30px)
UIImageView *imgViewCalendar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 10, 10)];
[imgViewCalendar setImage:[UIImage imageNamed:@"calendar_icon.png"]];
[viewRightIntxtFieldDate addSubview:imgViewCalendar];
txtFieldDate.rightViewMode = UITextFieldViewModeAlways;
txtFieldDate.rightView = viewRightIntxtFieldDate;
于 2014-01-14T11:38:42.733 回答
0

对于 Swift2 ,我使用

...
        self.mSearchTextField.leftViewMode = UITextFieldViewMode.Always
        let searchImg = UIImageView(image: UIImage(named: "search.png"))
        let size = self.mSearchTextField.frame.height
        searchImg.frame = CGRectMake(0, 0, size,size)
        searchImg.contentMode = UIViewContentMode.ScaleAspectFit
        self.mSearchTextField.leftView = searchImg
...
于 2016-05-23T15:07:57.690 回答
0

也许您可能会设置一个空视图并将您的视图嵌入为子视图:

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0))
imageView.contentMode = .center
imageView.image = UIImage(named: "ic_dropdown")
let emptyView = UIView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0))
emptyView.backgroundColor = .clear
emptyView.addSubview(imageView)
self.documentTypeTextLabel.rightView = emptyView
self.documentTypeTextLabel.rightViewMode = .always

在此处输入图像描述

快乐编码

于 2021-07-12T18:38:30.623 回答
0
...
textField.rightView = UIImageView(image: ...)
textField.rightView?.contentMode = .top
textField.rightView?.bounds.size.height += 10
textField.rightViewMode = .always
...
于 2019-04-25T22:30:47.123 回答
0

简单的方法:

textField.rightViewMode = .always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 15))
textField.contentMode = .scaleAspectFit
imageView = UIImage(named: "imageName")
textField.rightView = imageView

注意:高度应小于宽度以允许水平填充。

于 2019-06-19T03:48:54.857 回答
0

最简单的方法是将文本字段更改为 RoundRect 而不是 Custom 并查看魔术。:)

于 2016-03-17T12:25:12.250 回答
0

我意识到这是一个旧帖子,这个答案对我的用例有点特定,但我发布它以防其他人正在寻求类似的解决方案。我想移动 UITextField 的 leftView 或 rightView,但我没有将图像放入其中,也不想要任何硬编码常量。

我的 UI 要求隐藏文本字段的清除按钮并显示清除按钮所在的 UIActivityIndi​​catorView。

rightViewclearButton. 我不喜欢使用幻数,因为 clearButton 和 rightView 的位置随时可能被 Apple 更改。UI 设计意图是“清除按钮所在的微调器”,所以我的解决方案是继承 UITextField 并覆盖rightViewRect(forBounds)

override func rightViewRect(forBounds bounds: CGRect) -> CGRect {

    // Use clearButton's rectangle
    return self.clearButtonRect(forBounds: bounds)
}

下面是一个工作示例(无故事板):

//------------------------------------------------------------------------------
class myCustomTextField: UITextField {

    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {

        // Use clearButton rectangle
        return self.clearButtonRect(forBounds: bounds)
    }
}

//------------------------------------------------------------------------------
class myViewController: UIViewController {

    var activityView: UIActivityIndicatorView = {
        let activity = UIActivityIndicatorView()
        activity.startAnimating()
        return activity
    }()

    @IBOutlet weak var searchTextField: myCustomTextField!

    //------------------------------------------------------------------------------
    // MARK: - Lifecycle
    //------------------------------------------------------------------------------
    override func viewDidLoad() {

        super.viewDidLoad()

        searchTextField.rightView = activityView
        searchTextField.rightViewMode = .never // Hide spinner
        searchTextField.clearButtonMode = .never // Hide clear button

        setupUIForTextEntry()
    }

    // ...
    // More code to switch between user text entry and "search progress" 
    // by calling setupUI... functions below
    // ...

    //------------------------------------------------------------------------------
    // MARK: - UI
    //------------------------------------------------------------------------------
    func setupUIForTextEntry() {

        // Hide spinner
        searchTextField.rightViewMode = .never

        // Show clear button
        searchTextField.clearButtonMode = .whileEditing
        searchTextField.becomeFirstResponder()
    }

    //------------------------------------------------------------------------------
    func setupUIForSearching() {

        // Show spinner
        searchTextField.rightViewMode = .always

        // Hide clear button
        searchTextField.clearButtonMode = .never
        searchTextField.resignFirstResponder()
    }

    //------------------------------------------------------------------------------

}

//------------------------------------------------------------------------------
于 2020-02-14T18:21:00.840 回答