我要在屏幕上添加UITextView并添加约束,但是它不会显示在视图上。
class ViewController: UIViewController {
let balanceTitle: UITextView = {
let textView = UITextView();
textView.text = "hello balance";
textView.translatesAutoresizingMaskIntoConstraints = false;
textView.textColor = .red;
textView.backgroundColor = .gray;
return textView;
}()
let labelTitle: UILabel = {
let lblView = UILabel();
lblView.text = "mmsmsmsmsmsmsmsm";
lblView.textColor = .red;
lblView.translatesAutoresizingMaskIntoConstraints = false;
return lblView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//view.backgroundColor = .gray
//view.addSubview(balanceTitle)
view.addSubview(balanceTitle);
balanceTitle.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true;
balanceTitle.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true;
balanceTitle.heightAnchor.constraint(equalToConstant: 400).isActive = true;
}
}
答案 0 :(得分:1)
您需要添加宽度约束
NSLayoutConstraint.activate([
balanceTitle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
balanceTitle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
balanceTitle.heightAnchor.constraint(equalToConstant: 400),
balanceTitle.widthAnchor.constraint(equalToConstant: 200)
])
或者像这样获取视图比例值
balanceTitle.widthAnchor.constraint(equalTo:view.widthAnchor, multiplier: 0.8)