Swift UITextView用约束不可见

时间:2019-07-10 14:14:15

标签: ios swift xcode autolayout uitextview

我要在屏幕上添加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;
    }


}

下面是运行代码后得到的结果。 enter image description here

1 个答案:

答案 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)