swift - UITextField 的 leftView 上的图像未呈现
问题描述
我有一个UITextField
我想在左侧设置图标图像的地方。这是我的代码。谁能指出我的错误?
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.bounds.height/2
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor.white.cgColor
self.leftViewMode = .always
let iconImageView = UIImageView(frame: CGRect(x: 5, y: 5, width: self.bounds.height - 10, height: self.bounds.height - 10))
iconImageView.image = UIImage(named: "email")
let iconView = UIView()
iconView.frame = iconImageView.bounds
iconView.addSubview(iconImageView)
self.leftView = iconView
self.tintColor = .white
}
解决方案
以下是如何以编程方式创建自定义字段。
从这里你也可以得到将图标设置为 textField 的想法。
class ViewController: UIViewController {
///Creating textField
private let textField: UITextField = {
let tf = UITextField()
tf.leftViewMode = .always
tf.borderStyle = .line
let iconImageView = UIImageView()
iconImageView.image = UIImage(named: "HomeSelected")
iconImageView.contentMode = .scaleAspectFill
let iconView = UIView()
/// Settiing height iconView
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.heightAnchor.constraint(equalToConstant: 50).isActive = true
iconView.widthAnchor.constraint(equalToConstant: 50).isActive = true
iconView.addSubview(iconImageView)
/// Applying constraints to iconImageView
iconImageView.translatesAutoresizingMaskIntoConstraints = false
iconImageView.topAnchor.constraint(equalTo: iconView.topAnchor, constant: 5).isActive = true
iconImageView.leftAnchor.constraint(equalTo: iconView.leftAnchor, constant: 5).isActive = true
iconImageView.bottomAnchor.constraint(equalTo: iconView.bottomAnchor, constant: -5).isActive = true
///Setting height of iconImageView
iconImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
iconImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
tf.leftView = iconView
// Setting Height of Textfield
tf.translatesAutoresizingMaskIntoConstraints = false
tf.heightAnchor.constraint(equalToConstant: 50).isActive = true
return tf
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(textField)
///Apply constraints to text Field.
}
}
结果
推荐阅读
- regex - 从 actionlink html 响应正文中提取值 - JMeter
- html - 如何在没有 http(s) 的情况下使用 iframe src
- php - 为什么我的 Ajax/php 请求被执行了两次?
- node.js - 使用 node.js 的无服务器不会部署一些依赖项 node_modules
- android - 面临空指针异常,从android内部存储中获取文件
- javascript - 默认情况下为所有 v-text-field 概述的 Vuetify 集
- c# - 如何从日志中删除默认的 serilog 属性?
- sql - T-SQL 如何根据字段值是否存在来汇总事务?
- c# - 如何在asp.net mvc中将两个变量组合为一个变量?
- express - 使用 Express 将解码后的 POST 数据转发到其他 URL