iOS7上的UITextfield leftView / rightView填充

时间:2013-10-14 23:39:43

标签: ios objective-c uitextfield

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

28 个答案:

答案 0 :(得分:160)

一个更简单的解决方案,它利用了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 2中,

    let arrow = UIImageView(image: UIImage(named: "down_arrow"))
    arrow.frame = CGRectMake(0.0, 0.0, arrow.image.size.width+10.0, arrow.image.size.height);
    arrow.contentMode = UIViewContentMode.Center
    self.textField.rightView = arrow
    self.textField.rightViewMode = UITextFieldViewMode.Always

在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

答案 1 :(得分:79)

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

- (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并将class属性更改为此新子类的名称

答案 2 :(得分:42)

最简单的方法是在leftView / righView中添加一个UIView,并将一个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];

答案 3 :(得分:11)

这适用于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

答案 4 :(得分:6)

这对我有用

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

它可以帮助你。

答案 5 :(得分:4)

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

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

注意:..或2,如果你考虑包括QuartzCore一行:)

答案 6 :(得分:3)

快捷键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

答案 7 :(得分:3)

执行此操作的最佳方法是使用UITextField的子类并在.m文件中创建一个类

  #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;

}

通过执行此操作转到故事板或xib并单击身份检查器并将UITextfield替换为您自己的&#34; CustomTextField&#34;在课堂上选择。

注意:如果您只是为textfield提供自动布局的填充,那么您的应用程序将无法运行并仅显示空白屏幕。

答案 8 :(得分:2)

我在某个地方找到了......

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

[self addSubview:itemDescription];

答案 9 :(得分:1)

创建自定义UITextField类并使用该类而不是UITextField。覆盖 - (CGRect)textRectForBounds:(CGRect)边界设置你需要的矩形

实施例

- (CGRect)textRectForBounds:(CGRect)bounds{
     CGRect textRect = [super textRectForBounds:bounds];
     textRect.origin.x += 10;
     textRect.size.width -= 10;
     return textRect;
}

答案 10 :(得分:1)

//设置UITextField的Rightview,快速4.2 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

答案 11 :(得分: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
    }
}

答案 12 :(得分: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
}

答案 13 :(得分:1)

我自己遇到过这个问题,到目前为止最简单的解决办法就是修改图像,只需在图像的每一边添加填充!

我刚刚改变了我的png图像,添加了10像素的透明填充,效果很好,根本没有编码!

答案 14 :(得分:0)

谢谢你们的答案,令我惊讶的是,他们没有真正将正确的视图图像安装到我的文本字段,同时仍然提供所需的填充。然后我想到使用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的高度,可随意根据您的需要进行调整。

答案 15 :(得分:0)

- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.size.width - 40, 0, 40, bounds.size.height);
}

答案 16 :(得分:0)

如果你使用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;
}

答案 17 :(得分:0)

最简单的方法就是将Textfield更改为RoundRect而不是Custom,看看魔术。 :)

答案 18 :(得分: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
...

答案 19 :(得分:0)

我们可以重写apple提供的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*/

}

答案 20 :(得分:0)

...
textField.rightView = UIImageView(image: ...)
textField.rightView?.contentMode = .top
textField.rightView?.bounds.size.height += 10
textField.rightViewMode = .always
...

答案 21 :(得分: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

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

答案 22 :(得分:0)

下面的示例是将水平填充添加到恰好是图标的左视图中 - 您可以使用类似的方法将填充添加到您希望用作文本字段左视图的任何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的子类,但我相信这是最干净的方法。

答案 23 :(得分:0)

我在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方法)中调用该方法并将任何TextFields发送到该方法并为左右两侧添加填充,并通过只写一个来提供文本和背景颜色代码行,如下:

[self modifyTextField:self.firstNameTxtFld];

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

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

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

干杯!

答案 24 :(得分:0)

我意识到这是一篇过时的文章,并且这个答案有点针对我的用例,但是我发布了它,以防其他人寻求类似的解决方案。我想移动UITextField的leftView或rightView,但是我不想在其中放置图像,也不需要任何硬编码的常量。

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

我向rightView添加了一个微调器,但是开箱即用(在iOS 13上)它在clearButton的右边移动了20个像素。我不喜欢使用幻数,因为clearButton和rightView的位置随时可能被Apple更改。 UI设计的意图是“旋转按钮,其中清除按钮位于其中” ,因此我的解决方案是将UITextField子类化并覆盖rightViewRect(forBounds)

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

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

下面是一个有效的示例(没有Storyboard):

//------------------------------------------------------------------------------
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()
    }

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

}

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

答案 25 :(得分:0)

一招:将包含UIImageView的UIView添加到UITextField作为rightView。这个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;

答案 26 :(得分:0)

这是一个解决方案:

 UIView *paddingTxtfieldView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 42)]; // what ever you want 
 txtfield.leftView = paddingTxtfieldView;
 txtfield.leftViewMode = UITextFieldViewModeAlways;

答案 27 :(得分: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

enter image description here

快乐编码