我在设置包含单个数字的UITextView时遇到问题。我希望视图很小,文本在水平和垂直方向都在中心。
实例化视图:
let setNumberView: UITextView = {
let view = UITextView(frame: CGRect(x: 0, y: 0, width: heightForView(text: "8", font: UIFont.systemFont(ofSize: 12), width: 25), height: heightForView(text: "8", font: UIFont.systemFont(ofSize: 12), width: 25)))
view.text = "1"
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
print("FONT SIZE: \(view.font?.pointSize)")
return view
}()
设置约束:
/* setNumberView */
let setDiameter = heightForView(text: "8", font: UIFont.systemFont(ofSize: 12), width: 25)
addConstraintsWithFormat("H:|-4-[v0]", views: setNumberView)
addConstraint(NSLayoutConstraint(item: setNumberView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
//height
addConstraint(NSLayoutConstraint(item: setNumberView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: setDiameter))
//width
addConstraint(NSLayoutConstraint(item: setNumberView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: setDiameter))
但我留下了这个:
我的目标是让白色框中的“1”水平和垂直居中。
以下是我获得高度/宽度的方法:
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
答案 0 :(得分:0)
试试这个:
textView.textContainerInset = UIEdgeInsets.zero
textView.textContainer.lineFragmentPadding = 0