【问题标题】:UITextfield gets cut from the top while in editing modeUITextfield 在编辑模式下从顶部被剪切
【发布时间】:2017-03-21 22:36:22
【问题描述】:

我有两个 UITextfields,它们之间有分隔符(UILabel)。 我把它们都放到了 UIStackView 中。

在编辑模式下,文本字段的内容从顶部被剪切,如下图所示

我发现解决这个问题的唯一方法是使这个分隔符足够大,但这破坏了我的设计。

如何解决?

值得一提的是我的 UIStackView 设置:

并展示我如何实现这个自定义底线样式的 UITextfield

class CustomTextField: UITextField {

override func awakeFromNib() {
    super.awakeFromNib()

    let attributedString = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName:UIColor.lightGray, NSFontAttributeName: UIFont(name: "GothamRounded-Book", size: 18.0)! ])
    self.attributedPlaceholder = attributedString
    self.tintColor = UIColor.appRed
    self.font = UIFont(name: "GothamRounded-Book", size: 18.0)!
    self.borderStyle = .none
    self.textAlignment = .center

}


override func textRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: 0, dy: 5)
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: 0, dy: 5)
}


override var tintColor: UIColor! {

    didSet {
        setNeedsDisplay()
    }
}

override func draw(_ rect: CGRect) {

    let startingPoint   = CGPoint(x: rect.minX, y: rect.maxY)
    let endingPoint     = CGPoint(x: rect.maxX, y: rect.maxY)

    let path = UIBezierPath()

    path.move(to: startingPoint)
    path.addLine(to: endingPoint)
    path.lineWidth = 2.0

    tintColor.setStroke()
    tintColor = UIColor.appRed

    path.stroke()
}

}

非常感谢任何帮助

编辑

我有另一个这样的 TextField,它工作正常,但它不在任何水平 UIStackView 内。这是层次结构的截图:

【问题讨论】:

  • 我建议您查看菜单中的视图层次结构 -> 调试 -> 视图调试 -> 捕获视图层次结构(当然在模拟器运行时)
  • 是在编辑文本字段时捕获的图像
  • 嗯,不,抱歉,我马上修改
  • @zombie 请看上面
  • 在我看来编辑高度小于要求,所以可能在 intrinsicContentSize 和 isEditing 尝试提供更大的高度

标签: ios swift uitextfield uistackview


【解决方案1】:

不幸的是,您需要在编辑时检查大小

class CustomTextField: UITextField {
   override func awakeFromNib() {
      super.awakeFromNib()
      self.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
   }

   func textFieldEditingChanged(_ textField: UITextField) {
      textField.invalidateIntrinsicContentSize()
   }


   override var intrinsicContentSize: CGSize {
      if isEditing {
         let string = text ?? ""
         let size = string.size(attributes: typingAttributes)
         return CGSize(width: size.width + (rightView?.bounds.size.width ?? 0) + (leftView?.bounds.size.width ?? 0) + 2,
                       height: size.height)
      }

      return super.intrinsicContentSize
   }
}

【讨论】:

  • 不幸的是它不起作用,文本字段的行为与以前相同:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2018-03-11
  • 1970-01-01
  • 2018-02-19
  • 2023-04-01
  • 2017-03-04
相关资源
最近更新 更多