Swift在UITextField中添加图标/图像

时间:2015-01-12 13:50:46

标签: ios image swift login uitextfield

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

enter image description here

我试过了:

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

感谢。

20 个答案:

答案 0 :(得分:105)

Sahil有一个很好的答案,我想把它扩展为@IBDesignable,以便开发人员可以在故事板上的UITextFields中添加图像。

Swift 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的左边缘和图像
  • 之间添加填充
  • 设置颜色,使图像和占位符文本匹配

备注

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

可在故事板中设计 Storyboard

在运行时 Runtime

答案 1 :(得分:88)

尝试添加emailField.leftViewMode = UITextFieldViewMode.Always

(默认leftViewModeNever

更新了 Swift 4

的答案
emailField.leftViewMode = UITextFieldViewMode.always

emailField.leftViewMode = .always

答案 2 :(得分:42)

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

如果您想在左侧的 <LinearLayout android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:layout_height="wrap_content"> <View android:id="@+id/operatorLine" android:layout_width="180px" android:layout_height= "7dp" android:layout_marginRight="95px" android:background="#ffffff" /> <View android:id="@+id/adminLine" android:layout_width="155px" android:layout_marginLeft="95px" android:layout_height= "7dp" android:background="#ffffff" /> </LinearLayout> 上添加图片,请使用UITextField

leftView属性

注意: 请勿忘记将UITextField设置为leftViewMode,将UITextFieldViewMode.Always设置为rightViewMode默认为UITextFieldViewMode.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上添加

    让imageView = UIImageView(框架:CGRect(x:0,y:0,宽度:20,高度:20))

  • 如果您的图片背景为白色,则图片在UITextField

  • 上无法显示
  • 如果您想将图片添加到特定位置,则需要将UITextField添加为ImageView的子视图。

更新Swift 3.0

@Mark Moeykens精彩地消耗它并使其 @IBDesignable

我修改并添加了一些功能(在右图中添加底线和填充)。

注意如果您想在右侧添加图片,可以在界面制作工具的UITextField中选择Force Right-to-Left选项(但是对于右图片填充获胜&#39 ; t工作,直到你将覆盖rightViewRect方法)。

enter image description here

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

下载源代码

enter image description here

答案 3 :(得分:12)

UITextField with image (left or right)

另一种方式,灵感来自之前的帖子进行扩展。

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

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

享受:)

答案 4 :(得分:6)

for 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

答案 5 :(得分:5)

2020-合理的解决方案

关于苹果公司的这种疯狂。

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

enter image description here

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

请注意以下关键质量检查: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
        }
    }
}

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

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

}

答案 7 :(得分:3)

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

enter image description here

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

答案 8 :(得分:2)

Swift 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
        }
    }

}

答案 9 :(得分:2)

enter image description here
另一种设置占位符图标和方式的方法将填充设置为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
}

答案 10 :(得分:1)

为什么不采用最简单的方法。对于大多数情况,你想添加像字体真棒的图标...只需使用字体真棒库,就像这样容易将文字字段添加到文本字段:

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

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

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

答案 12 :(得分:1)

使用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")

输出:)

enter image description here

答案 13 :(得分:0)

这为我做到了。在自定义/可重用的类中。有助于大量使用黑白中的实际文本和左视图图标/图像enter image description here

func currencyLeftVeiw(image litery: UIImage) {
        self.leftView = UIView(frame: CGRect(x: 10, y: 0, width: 40, height: 40))
        self.leftViewMode = .always
        let leftViewItSelf = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
        leftViewItSelf.image = litery
        leftView?.addSubview(leftViewItSelf)
    }

答案 14 :(得分:0)

let image = UIImage(systemName: "envelope")
let textField = UITextField()
textField.leftView = UIImageView(image: image)
textField.leftView?.frame = CGRect(x: 5, y: 5, width: 20 , height:20)
textField.leftViewMode = .always

答案 15 :(得分:0)

我认为基于框架的解决方案不是一个好方法,因为在某些情况下,iPad无法使用该解决方案。 理想的解决方案是在imageView到textfield的右视图中添加约束,但这并不容易。除非需要,否则右视图似乎不会出现在文本字段视图层次结构中,因此您需要执行以下操作:

    private let countryTextField: UITextField = {
        let countryTextField = UITextField()
        countryTextField.translatesAutoresizingMaskIntoConstraints = false
        countryTextField.rightViewMode = .always
        
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "yourImageName"), for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        
        countryTextField.rightView = button
        countryTextField.setNeedsLayout() //Add rightView in textField hierarchy
        countryTextField.layoutIfNeeded() //Add rightView in textField hierarchy
        
        button.topAnchor.constraint(equalTo: countryTextField.topAnchor).isActive = true
        button.bottomAnchor.constraint(equalTo: countryTextField.bottomAnchor).isActive = true
        button.widthAnchor.constraint(equalTo: countryTextField.heightAnchor).isActive = true
        
        return countryTextField
    }()

在任何设备上的结果是:

TextField right view

此外,我的解决方案适用于文本字段左视图。

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

Results

答案 17 :(得分:0)

快速5

类似于@Markus,但在 Swift 5 中:

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

答案 18 :(得分:0)

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

结果

enter image description here

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