图1中,粉色半透明框为textview,placeholder_label在其下方。
二者约束分布如下:
图2 textview约束 图3 placeholderLabel约束
图1布局可以看到,textview与placeholder_label文字并未对其。添加以下代码,运行后二者首行首字可对齐。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textview.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
以下是动态自适应高度关键代码(输入换行时,自动增加textview高度):
extension CRWithdrawViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if let text = textView.text {
var finalText = text
if text.count > 140 {//限制输入140个字符
finalText = String(text.prefix(140))
}
textView.text = finalText
if finalText == "" {
placeholder_label.isHidden = false
}else {
placeholder_label.isHidden = true//有输入内容时隐藏placeholder
}
let size = CGSize(width: ScreenWidth() - 16, height: CGFloat(MAXFLOAT))
//注意,sizeThatFits方法并不会真正改变textview的frame,而是返回一个与给定size匹配最佳的frame
let resultSize = textview.sizeThatFits(size)
let fitHeight = resultSize.height
textview_height.constant = fitHeight > 20 ? fitHeight : 20//如果高度<20,则强制设为20
}else{
//text = nil?
placeholder_label.isHidden = false
textview_height.constant = 20
}
}
}
运行效果
网友评论