How to get left padding on UITextField leftView image?

元气小坏坏 提交于 2019-11-30 21:02:48

you can simply try this:

    UIImageView *envelopeView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, 30, 30)];
    envelopeView.image = [UIImage imageNamed:@"comment-128.png"];
    envelopeView.contentMode = UIViewContentModeScaleAspectFit;
  UIView *test=  [[UIView alloc]initWithFrame:CGRectMake(20, 0, 30, 30)];
    [test addSubview:envelopeView];
    [self.textField.leftView setFrame:envelopeView.frame];
    self.textField.leftView =test;
        self.textField.leftViewMode = UITextFieldViewModeAlways;
Fitsyu

For Swift 3 Users

Here is what worked for me:

extension UITextField {

 /// set icon of 20x20 with left padding of 8px 
 func setLeftIcon(_ icon: UIImage) {

    let padding = 8
    let size = 20

    let outerView = UIView(frame: CGRect(x: 0, y: 0, width: size+padding, height: size) )
    let iconView  = UIImageView(frame: CGRect(x: padding, y: 0, width: size, height: size))
    iconView.image = icon
    outerView.addSubview(iconView)

    leftView = outerView
    leftViewMode = .always  
  }
}

test:

txOrigin.setLeftIcon(icon_location)

result:

Garima Saini

You can use this. Change your frame according to your need.

NSTextAttachment*   placeholderImageTextAttachment = [[NSTextAttachment alloc] init];
placeholderImageTextAttachment.image = [UIImage imageNamed:@"Search"];
placeholderImageTextAttachment.bounds = CGRectMake(0, -2, 16, 16);
NSMutableAttributedString*  placeholderImageString = [[NSAttributedString attributedStringWithAttachment:placeholderImageTextAttachment] mutableCopy];
 NSMutableAttributedString*  placeholderString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"   Search", nil)];
[placeholderImageString appendAttributedString:placeholderString];
 _txtFieldSearch.attributedPlaceholder = placeholderImageString;
_txtFieldSearch.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!