【问题标题】:Content of UITextFiled gets trimmed when removing the border删除边框时,文本字段的内容被修剪
【发布时间】:2018-02-06 04:06:28
【问题描述】:

对于我的 UITextField,我希望删除边框。因此,我尝试将其边框颜色更改为背景颜色(边框宽度为 1),但这样做会在角落看到模糊的边框线。接下来,我在属性检查器中将边框样式设置为无。当我运行应用程序时,边框消失了。但是,当在其中输入文本时,文本会在左侧被裁剪,如图所示。我尝试将填充视图添加到文本字段,但它没有解决问题。我该如何解决这个问题?

编辑:

文本字段后跟一个标签。由于我希望标签跟随文本字段的内容,因此我没有设置文本字段的宽度。如图所示。当我将 leftViewMode 添加为 always 的填充视图时,设计未呈现,我收到控制台消息:

- 在仅变换层中更改属性 maskToBounds,将无效

根据@Surjeet 链接中的一个答案,我尝试将 textField 扩展为:

class CustomTextField: UITextField {

    required init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.size.width, height: bounds.size.height)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return self.textRect(forBounds: bounds)
    }
}

但问题仍然没有解决。

【问题讨论】:

  • 如何在 UITextField 中添加填充?有一些问题,应该通过左填充来修复。
  • 让 paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: self.myTextField.frame.height)) myTextField.leftView = paddingView 这样对吗?
  • 检查this link,添加一个属性**leftViewMode**。试试这个。
  • 你能分享一下,你到目前为止都试过什么吗?

标签: ios swift uitextfield border


【解决方案1】:

您可以为您的文本字段添加左填充,您的问题应该得到解决。

斯威夫特 4

        let paddingView: UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
        textField.leftView = paddingView
        textField.leftViewMode = .always

【讨论】:

  • 嘿@Sujal 你觉得我的回答有帮助吗?
【解决方案2】:
text_field.setLeftPaddingPoints(10)

text_field.setRightPaddingPoints(10)


extension UITextField {

    func setLeftPaddingPoints(_ amount:CGFloat){
       let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
       self.leftView = paddingView
       self.leftViewMode = .always
    }
    func setRightPaddingPoints(_ amount:CGFloat) {
      let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
      self.rightView = paddingView
      self.rightViewMode = .always
    }
}

【讨论】:

  • 虽然您所写的内容可能会回答这个问题,但在explanation 中似乎确实缺少一些内容,并且可能会给其他用户造成非法混淆。您能否扩展您的答案,使其更清晰、更易于理解?这将提供更好的答案,并帮助未来的用户了解问题是如何解决的。
猜你喜欢
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
相关资源
最近更新 更多