IBTextField.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // IBTextField.swift
  3. // MTP2_iOS
  4. //
  5. // Created by zhongyuan on 2018/3/17.
  6. // Copyright © 2018年 zhongyuan.All rights reserved.
  7. //
  8. import UIKit
  9. @IBDesignable
  10. class IBTextField: UITextField {
  11. /// 集成IBView 参数
  12. @IBInspectable var 圆角偏移量: CGFloat = 0.0
  13. @IBInspectable var 圆角倍数: CGPoint = CGPoint.init(x: 0, y: 0)
  14. @IBInspectable var maskToBounds: Bool = false
  15. @IBInspectable var borderColor: UIColor = UIColor.clear
  16. @IBInspectable var borderWidth: CGFloat = 0.0
  17. /// IBTextField参数
  18. @IBInspectable var insetLeft: CGFloat = 0.0
  19. @IBInspectable var insetRight: CGFloat = 0.0
  20. @IBInspectable var isNeedRightView: Bool = false {
  21. didSet {
  22. if !isNeedRightView {
  23. rightView = nil
  24. rightViewMode = .always
  25. return
  26. }
  27. rightView = UIImageView(image: rightImage)
  28. (rightView as? UIImageView)?.contentMode = .scaleAspectFit
  29. rightViewMode = .always
  30. }
  31. }
  32. @IBInspectable var rightImage: UIImage? = UIImage(named: "pull") {
  33. didSet {
  34. if !isNeedRightView { return }
  35. rightView = UIImageView(image: rightImage)
  36. rightViewMode = .always
  37. }
  38. }
  39. @IBInspectable var rightImageRightInsert: CGFloat = 0.0
  40. private static let checkValueBlock = {(rect: CGRect,target: IBTextField) -> CGRect in
  41. guard let l:Double = target.value(forKey:"insetLeft") as? Double,
  42. let r:Double = target.value(forKey:"insetRight") as? Double else { return CGRect.init() }
  43. return CGRect.init(x: CGFloat(l),
  44. y: 0,
  45. width: rect.size.width - CGFloat(l) - CGFloat(r),
  46. height: rect.size.height)
  47. }
  48. override func layoutSubviews() {
  49. super.layoutSubviews()
  50. IBView.refreshIBEffect(view: self)
  51. }
  52. /// UITextField 文字与输入框的距离
  53. override func textRect(forBounds bounds:CGRect) -> CGRect {
  54. let rect:CGRect = super.textRect(forBounds: bounds)
  55. return IBTextField.checkValueBlock(rect, self)
  56. }
  57. /// 控制文本的位置
  58. override func editingRect(forBounds bounds: CGRect) -> CGRect {
  59. let rect:CGRect = super.editingRect(forBounds: bounds)
  60. return IBTextField.checkValueBlock(rect, self)
  61. }
  62. /// 控制rightView的距离
  63. override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
  64. var rect:CGRect = super.rightViewRect(forBounds: bounds)
  65. rect.origin.x -= rightImageRightInsert
  66. return rect
  67. }
  68. }