昨天介紹完客製化按鈕,今天會分享客製化文字輸入框( 加入圖示、圖示顯示在左邊或右邊 )
成品:
刻好畫面後,在 ViewController.swift ( MainVC.swift ) 加入程式碼
在專案底下 New Group / New File / 選 Cocoa Touch Class
設置左圖與左邊界的距離、右視圖與右邊界的距離
設定邊界初始值
設置圖示選項
設置圖示顏色
設定圖示限制與大小
在 MainVC -> TextField -> Class
選擇剛剛建立的客製化文字輸入框的檔案名稱
選完後就會多了這些性質可以做變更
若圖示在左邊,則需修改 Left Padding 的數值
若要將圖示顯示在右邊,則修改此選項,將其改成 Force Right-to-Left
並且修改 Right Padding 的數值
附上完整程式碼
// MainVC.swift
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var btn: UIButton!
@IBOutlet weak var txf: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
}
// CustomTextField.swift
import UIKit
@IBDesignable
class CustomTextField: UITextField {
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var leftTextRect = super.leftViewRect(forBounds: bounds)
leftTextRect.origin.x += leftPadding
return leftTextRect
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var rightTextRect = super.rightViewRect(forBounds: bounds)
rightTextRect.origin.x -= rightPadding
return rightTextRect
}
@IBInspectable var leftImage: UIImage? { didSet { updateView() } }
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var rightPadding: 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
imageView.tintColor = color
leftView = imageView
}
else{
leftViewMode = UITextField.ViewMode.never
leftView = nil
}
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: color])
}
}
這樣就完成客製化文字輸入框啦!明天會分享新的實作,敬請期待!