【问题标题】:Text inset for UITextFieldUITextField 的文本插入
【发布时间】:2015-10-10 05:58:39
【问题描述】:

我已经看到这个帖子Text inset for UITextField?,但仍然无法弄清楚。

我想要一个 80.0 高的 UITextField。我希望文本比UITextField 的顶部低 40.0,高 20.0,在文本下方留下 20.0 作为填充。我目前的代码是。

let textBounds: CGRect = CGRect(x: 0, y: 40, width: self.width, height: 20)
self.editingRectForBounds(textBounds)
self.textRectForBounds(textBounds)

UITextField 是子类,目前我认为文本上下有 30.0 的填充,并且在 UITextField 内的高度或垂直居中为 20.0。

【问题讨论】:

    标签: ios uitextfield uikit swift2


    【解决方案1】:

    我已重写您的代码以使用 UITextField 子类:

    class myTextField: UITextField {
        var textBounds: CGRect = CGRectZero
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            textBounds = CGRectMake(0, 40, self.frame.width, 20)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func textRectForBounds(bounds: CGRect) -> CGRect {
            return textBounds
        }
    
        override func editingRectForBounds(bounds: CGRect) -> CGRect {
            return textBounds
        }    
    }
    

    并添加了一个如何将其添加到您的视图中的示例:

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let textField = myTextField(frame: CGRectMake(20, 64, 200, 50))
            textField.text = "Hello World"
    
             // Show a border to visualize the frame.
            textField.layer.borderColor = UIColor.redColor().CGColor
            textField.layer.borderWidth = 1
    
            view.addSubview(textField)
        }
    
    }
    

    UITextField 子类可以添加到您的视图控制器文件或单独的文件中。这是你的选择。

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      相关资源
      最近更新 更多