在UITextField中快速添加图标/图像


101

我想在UITextField中添加图标/图像。图标/图像应留给占位符。

在此处输入图片说明

我尝试了这个:

var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;

谢谢。


74
您不小心添加了分号:D
Gerald

10
emailField.leftView = UIImageView(image: UIImage(named: "search")):)
tspentzas

使用@IBDesignable本示例,我们可以以一种优雅的方式做到这一点:stackoverflow.com/a/51841433/8238512
Rizwan

Answers:


120

尝试添加 emailField.leftViewMode = UITextFieldViewMode.Always

(默认leftViewModeNever

更新了Swift 4的答案

emailField.leftViewMode = UITextFieldViewMode.always

emailField.leftViewMode = .always

嗯,它对我有用,您是否尝试过使用更新后的值(UITextFieldViewMode.Always)?您有什么想法是行不通的吗?(例如,它编译了吗?)
Markus

这是我在ViewWillAppear部分中的全部代码:var imageView = UIImageView(); var image = UIImage(named:“ email.png”); imageView.image =图片;emailTextField.leftView = imageView; emailTextField.leftViewMode = UITextFieldViewMode.Always
informatiker

@informatiker好,那么,如果您设置了的背景颜色,那么您确定连接正确emailTextField吗?并且您确定图像在那里吗?例如,创建另一个UIImageView并image在该UIImageView中加载,以验证其是否有效。
马库斯

4
对了谢谢。问题在于该图标为白色,在白色背景上不可见。
信息通报

5
我继续搜索并最终使它起作用,但我没有为图像视图设置框架。看起来我们需要在图像上设置框架,然后再将其添加到uitextfield中。像这样imageView1.frame = CGRect(x: 5, y: 0, width: userName.frame.height, height: userName.frame.height) view.addSubview(imageView1)
Sashi 2015年

123

萨希尔(Sahil)有一个很好的答案,我想将其扩展为@IBDesignable,以便开发人员可以将图像添加到情节提要上的UITextField中。

斯威夫特4.2

import UIKit

@IBDesignable
class DesignableUITextField: UITextField {
    
    // Provides left padding for images
    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var textRect = super.leftViewRect(forBounds: bounds)
        textRect.origin.x += leftPadding
        return textRect
    }
    
    @IBInspectable var leftImage: UIImage? {
        didSet {
            updateView()
        }
    }
    
    @IBInspectable var leftPadding: CGFloat = 0
    
    @IBInspectable var color: UIColor = UIColor.lightGray {
        didSet {
            updateView()
        }
    }
    
    func updateView() {
        if let image = leftImage {
            leftViewMode = UITextField.ViewMode.always
            let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
            imageView.contentMode = .scaleAspectFit
            imageView.image = image
            // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
            imageView.tintColor = color
            leftView = imageView
        } else {
            leftViewMode = UITextField.ViewMode.never
            leftView = nil
        }
        
        // Placeholder text color
        attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: color])
    }
}

这是怎么回事

这个可设计的项目使您能够:

  • 在左侧设置图片
  • 在UITextField的左边缘和图像之间添加填充
  • 设置颜色,使图像和占位符文本匹配

笔记

  • 要更改图像颜色,您必须遵循代码注释中的注释
  • 情节提要中的图像颜色不会改变。您必须运行项目才能在模拟器/设备中查看颜色。

可在情节提要中设计 故事板

在运行时 运行


5
在imageView.contentMode = .AspectFit中添加,以避免调整图像大小。
Jerland2

3
非常感谢您的精彩帖子!我已经对其进行了修改,使其也具有RTL选项。可用的代码在此处:pastebin.com/7CCm6NEB
Ali Almohsen

干得好,伙计们!我后来也做了同样的事情。哈哈
Mark Moeykens '17

14
图像和文字之间的填充呢?
Zaporozhchenko Oleksandr

1
很好的答案。
Ripa Saha

51

我只想在这里添加更多内容:

如果要UITextField在左侧添加图像,请使用的leftView属性UITextField

注意: 不要忘了一套leftViewModeUITextFieldViewMode.Always和为右rightViewModeUITextFieldViewMode.Always and默认为UITextFieldViewModeNever

例如

用于在左侧添加图像

textField.leftViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.leftView = imageView

用于在右侧添加图像

textField.rightViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.rightView = imageView

注意:UITextField在左侧或右侧添加图像时,需要注意一些事项。

  • 不要忘了给帧的ImageView哪一个是你要添加上UITextField

    让imageView = UIImageView(frame:CGRect(x:0,y:0,width:20,height:20))

  • 如果图像背景为白色,则图像在 UITextField

  • 如果要将图像添加到特定位置,则需要将其添加ImageView为的子视图UITextField

Swift 3.0更新

@Mark Moeykens精美地消耗了它并使它成为@IBDesignable

我在其中修改并添加了其他功能(为正确的图像添加了底线和填充)。

注意:如果要在右侧添加图像,可以在界面生成器中选择Force Right-to-Left选项semantic(但是对于右侧图像填充,除非您重写rightViewRect方法,否则将不起作用)。

在此处输入图片说明

我已对此进行了修改,可以从此处下载源ImageTextField

在此处输入图片说明


如何在扩展中添加此名称并在ViewController中调用?你能建议我吗
narahari_arjun

很简单!只需在UIViewController扩展中创建函数,并在调用该函数时传递imagename和textfield ref。
萨希尔

扩展UIViewController {func addLeftImage(imageName:String,textField:UITextField){textField.leftViewMode = UITextFieldViewMode。始终让imageView = UIImageView(frame:CGRect(x:0,y:0,width:20,height:20))让图像= UIImage(named:imageName)imageView.image = image textField.leftView = imageView}}并像self.addLeftImage(“ imganame”,textField:yourtextfield)一样调用它
Sahil

我试图更改图标位置。但使用此代码未更改
Rahul Phate '19

22

带有图像的UITextField(向左或向右)

从以前的帖子中获得灵感的另一种方法是进行扩展。

我们可以将图像放在右边或左边

extension UITextField {

enum Direction {
    case Left
    case Right
}

// add image to textfield
func withImage(direction: Direction, image: UIImage, colorSeparator: UIColor, colorBorder: UIColor){
    let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
    mainView.layer.cornerRadius = 5

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
    view.backgroundColor = .white
    view.clipsToBounds = true
    view.layer.cornerRadius = 5
    view.layer.borderWidth = CGFloat(0.5)
    view.layer.borderColor = colorBorder.cgColor
    mainView.addSubview(view)

    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    imageView.frame = CGRect(x: 12.0, y: 10.0, width: 24.0, height: 24.0)
    view.addSubview(imageView)

    let seperatorView = UIView()
    seperatorView.backgroundColor = colorSeparator
    mainView.addSubview(seperatorView)

    if(Direction.Left == direction){ // image left
        seperatorView.frame = CGRect(x: 45, y: 0, width: 5, height: 45)
        self.leftViewMode = .always
        self.leftView = mainView
    } else { // image right
        seperatorView.frame = CGRect(x: 0, y: 0, width: 5, height: 45)
        self.rightViewMode = .always
        self.rightView = mainView
    }

    self.layer.borderColor = colorBorder.cgColor
    self.layer.borderWidth = CGFloat(0.5)
    self.layer.cornerRadius = 5
}

}

用 :

if let myImage = UIImage(named: "my_image"){
    textfield.withImage(direction: .Left, image: myImage, colorSeparator: UIColor.orange, colorBorder: UIColor.black)
}

请享用 :)


1
您辛苦了,我自定义了“ view.backgroundColor”和“ imageView.tintColor”以使其完全可自定义。非常感谢您的回答xD
安德烈斯·帕拉迪内斯

1
这太棒了
Mohamed Haseel '19

1
这是最好,最简单的答案
Gerardo SalazarSánchez19年

14

为了创建填充,我喜欢将图像放置在容器视图内。对图标放置满意后,可以删除背景色。

在此处输入图片说明

let imageView = UIImageView(frame: CGRect(x: 8.0, y: 8.0, width: 24.0, height: 24.0))
let image = UIImage(named: "my_icon")
imageView.image = image
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = UIColor.red

let view = UIView(frame: CGRect(x: 0, y: 0, width: 32, height: 40))
view.addSubview(imageView)
view.backgroundColor = .green
textField.leftViewMode = UITextFieldViewMode.always
textField.leftView = view

谢谢。颜色很好的解释。
Hamid Reza Ansari

13

对于Swift 3.0,在textField的左侧添加图片

textField.leftView = UIImageView(image: "small-calendar")
textField.leftView?.frame = CGRect(x: 0, y: 5, width: 20 , height:20)
textField.leftViewMode = .always

6

迅捷5

@IBOutlet weak var paswd: UITextField! {
    didSet{
      paswd.setLeftView(image: UIImage.init(named: "password")!)
      paswd.tintColor = .darkGray
      paswd.isSecureTextEntry = true
    }   
 }

我已创建扩展

extension UITextField {
  func setLeftView(image: UIImage) {
    let iconView = UIImageView(frame: CGRect(x: 10, y: 10, width: 25, height: 25)) // set your Own size
    iconView.image = image
    let iconContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: 45))
    iconContainerView.addSubview(iconView)
    leftView = iconContainerView
    leftViewMode = .always
    self.tintColor = .lightGray
  }
}

结果

在此处输入图片说明


4

2020年-合理的解决方案

关于苹果的这种疯狂。

这也许是“最清晰”,最简单的方法:

在此处输入图片说明

首先,您必须正确移动文本。

请注意以下关键质量检查:https : //stackoverflow.com/a/27066764/294884

class TidyTextField: UITextField {
    
    @IBInspectable var leftImage: UIImage? = nil
    @IBInspectable var leftPadding: CGFloat = 0
    @IBInspectable var gapPadding: CGFloat = 0
    
    private var textPadding: UIEdgeInsets {
        let p: CGFloat = leftPadding + gapPadding + (leftView?.frame.width ?? 0)
        return UIEdgeInsets(top: 0, left: p, bottom: 0, right: 5)
    }
    
    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textPadding)
    }
    
    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textPadding)
    }
    
    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textPadding)
    }
    

继续,我们现在必须制作并移动左图:

    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var r = super.leftViewRect(forBounds: bounds)
        r.origin.x += leftPadding
        return r
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
    
    private func setup() {
        if let image = leftImage {
            if leftView != nil { return } // critical!
            
            let im = UIImageView()
            im.contentMode = .scaleAspectFit
            im.image = image
            
            leftViewMode = UITextField.ViewMode.always
            leftView = im
            
        } else {
            leftViewMode = UITextField.ViewMode.never
            leftView = nil
        }
    }
}

这似乎是最清晰,最可靠的方法。


3

我创建了一个简单的IBDesignable。使用它,但是你喜欢。只需让您的UITextField确认此类即可。

import UIKit

@IBDesignable
class RoundTextField : UITextField {
    @IBInspectable var cornerRadius : CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }

    @IBInspectable var borderWidth : CGFloat = 0 {
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor : UIColor? {
        didSet {
            layer.borderColor = borderColor?.cgColor
        }
    }

    @IBInspectable var bgColor : UIColor? {
        didSet {
            backgroundColor = bgColor
        }
    }

    @IBInspectable var leftImage : UIImage? {
        didSet {
            if let image = leftImage{
                leftViewMode = .always
                let imageView = UIImageView(frame: CGRect(x: 20, y: 0, width: 20, height: 20))
                imageView.image = image
                imageView.tintColor = tintColor
                let view = UIView(frame : CGRect(x: 0, y: 0, width: 25, height: 20))
                view.addSubview(imageView)
                leftView = view
            }else {
                leftViewMode = .never
            }

        }
    }

    @IBInspectable var placeholderColor : UIColor? {
        didSet {
            let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
            let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName : placeholderColor!])
            attributedPlaceholder = str
        }
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

}

3

在此处输入图片说明
设置占位符图标和将填充设置为TextField的另一种方法。

let userIcon = UIImage(named: "ImageName") 
setPaddingWithImage(image: userIcon, textField: txtUsername)

func setPaddingWithImage(image: UIImage, textField: UITextField){
    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 50))
    imageView.frame = CGRect(x: 13.0, y: 13.0, width: 24.0, height: 24.0)
    //For Setting extra padding other than Icon.
    let seperatorView = UIView(frame: CGRect(x: 50, y: 0, width: 10, height: 50))
    seperatorview.backgroundColor = UIColor(red: 80/255, green: 89/255, blue: 94/255, alpha: 1)
    view.addSubview(seperatorView)
    textField.leftViewMode = .always
    view.addSubview(imageView)
    view.backgroundColor = .darkGray
    textField.leftViewMode = UITextFieldViewMode.always
    textField.leftView = view
}

2

斯威夫特3.1

extension UITextField
{
    enum Direction
    {
        case Left
        case Right
    }

    func AddImage(direction:Direction,imageName:String,Frame:CGRect,backgroundColor:UIColor)
    {
        let View = UIView(frame: Frame)
        View.backgroundColor = backgroundColor

        let imageView = UIImageView(frame: Frame)
        imageView.image = UIImage(named: imageName)

        View.addSubview(imageView)

        if Direction.Left == direction
        {
            self.leftViewMode = .always
            self.leftView = View
        }
        else
        {
            self.rightViewMode = .always
            self.rightView = View
        }
    }

}

请添加用法,我需要传递帧参数吗?
苏里亚·雷迪

此功能中的“框架”参数用于左视图或右视图
jethava yogesh 18-10-29

1

您可以将此函数放在全局文件中或放在类的上方,以便可以在整个应用程序中访问它。完成此过程后,您可以根据应用程序中的要求调用此函数。

        func SetLeftSIDEImage(TextField: UITextField, ImageName: String){

                let leftImageView = UIImageView()
                leftImageView.contentMode = .scaleAspectFit

                let leftView = UIView()

                leftView.frame = CGRect(x: 20, y: 0, width: 30, height: 20)
                leftImageView.frame = CGRect(x: 13, y: 0, width: 15, height: 20)
                TextField.leftViewMode = .always
                TextField.leftView = leftView

                let image = UIImage(named: ImageName)?.withRenderingMode(.alwaysTemplate)
                leftImageView.image = image
                leftImageView.tintColor = UIColor(red: 106/255, green: 79/255, blue: 131/255, alpha: 1.0)
                leftImageView.tintColorDidChange()

                leftView.addSubview(leftImageView)
            }

            SetLeftSIDEImage(TextField: Your_textField, ImageName:YourImageName) // call function

2
欢迎使用StackOverflow,有什么办法可以在这段代码中加上一些解释?其中仅包含代码的答案往往会因为质量低而被删除。也请在帮助部分中查看本指南进行回答:stackoverflow.com/help/how-to-answer
Graham

0

您为什么不选择最简单的方法。在大多数情况下,您想添加诸如字体真棒之类的图标...只需使用字体真棒库即可,将图标添加到文本字段就像这样简单:

myTextField.setLeftViewFAIcon(icon: .FAPlus, leftViewMode: .always, textColor: .red, backgroundColor: .clear, size: nil)

您需要首先安装此swift库:https : //github.com/Vaberer/Font-Awesome-Swift


5
为什么要只添加一个字形就添加整个库?

0

这是Mark Moeykens答案的修改版本,在图像和文本之间增加了填充,并在有人需要的情况下可调整图像大小。

斯威夫特4

    import UIKit

    @IBDesignable
    class TextFieldWithImage: UITextField {

        override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
            return super.leftViewRect(forBounds: bounds)
        }

        @IBInspectable var leftImage: UIImage? {
            didSet {
                updateView()
            }
        }
        @IBInspectable var leftPadding: CGFloat = 0 {
            didSet {
                updateView()
            }
        }
        @IBInspectable var rightPadding: CGFloat = 0 {
            didSet {
                updateView()
            }
        }
        @IBInspectable var imageMaxHeight: CGFloat = 0 {
            didSet {
                updateView()
            }
        }

        @IBInspectable var color: UIColor = UIColor.lightGray {
            didSet {
                updateView()
            }
        }

        func updateView() {
            if let image = leftImage {
                leftViewMode = UITextField.ViewMode.always

                let containerSize = calculateContainerViewSize(for: image)
                let containerView = UIView(frame: CGRect(x: 0, y: 0, width: containerSize.width, height: containerSize.height))

                let imageView = UIImageView(frame: .zero)
                containerView.addSubview(imageView)
                setImageViewConstraints(imageView, in: containerView)

                setImageViewProperties(imageView, image: image)

                leftView = containerView
            } else {
                leftViewMode = UITextField.ViewMode.never
                leftView = nil
            }

            attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "",
                    attributes: [NSAttributedString.Key.foregroundColor: color])
        }

        private func calculateContainerViewSize(for image: UIImage) -> CGSize {
            let imageRatio = image.size.height / image.size.width
            let adjustedImageMaxHeight = imageMaxHeight > self.frame.height ? self.frame.height : imageMaxHeight

            var imageSize = CGSize()
            if image.size.height > adjustedImageMaxHeight {
                imageSize.height = adjustedImageMaxHeight
                imageSize.width = imageSize.height / imageRatio
            }

            let paddingWidth = leftPadding + rightPadding

            let containerSize = CGSize(width: imageSize.width + paddingWidth, height: imageSize.height)
            return containerSize
        }

        private func setImageViewConstraints(_ imageView: UIImageView, in containerView: UIView) {
            imageView.translatesAutoresizingMaskIntoConstraints = false
            imageView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
            imageView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
            imageView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -rightPadding).isActive = true
            imageView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: leftPadding).isActive = true
        }

        private func setImageViewProperties(_ imageView: UIImageView, image: UIImage) {
            imageView.contentMode = .scaleAspectFit
            imageView.image = image
            imageView.tintColor = color
        }
    }

0

迅捷5

与@Markus类似,但在Swift 5中

emailTextField.leftViewMode = UITextField.ViewMode.always
emailTextField.leftViewMode = .always

0

SwiftUI

RoundedRectangle(cornerRadius: 50)
                .frame(height: 40)
                .colorInvert() // sets the background white
            .padding()
            .shadow(radius: 12) // adds shadow to the rectangle
                .overlay(
                    HStack(spacing: 20){

                        Image(systemName: "person")
                            .resizable()
                            .aspectRatio(contentMode: .fit)

                        TextField("Username ", text: $username)
                            .font(Font.custom("Arial", size: 25))


                            .font(.title)
                    }
                    .padding()
                    .padding()
                )

结果


0

使用Swift4中的扩展名,我们可以轻松地将图像放置在TextField的右侧或左侧。

extension UITextField {

    //MARK:- Set Image on the right of text fields

  func setupRightImage(imageName:String){
    let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
    imageView.image = UIImage(named: imageName)
    let imageContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 40))
    imageContainerView.addSubview(imageView)
    rightView = imageContainerView
    rightViewMode = .always
    self.tintColor = .lightGray
}

 //MARK:- Set Image on left of text fields

    func setupLeftImage(imageName:String){
       let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
       imageView.image = UIImage(named: imageName)
       let imageContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 40))
       imageContainerView.addSubview(imageView)
       leftView = imageContainerView
       leftViewMode = .always
       self.tintColor = .lightGray
     }

  }

使用代码作为左图像设置:-

   self.password_text_field.setupLeftImage(imageName: "unlock")

输出:)

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.