Swift视图未显示

时间:2019-08-20 14:04:15

标签: ios swift

我试图在主视图上创建一个UITextView,我设法用textView = UITextView(frame: CGRect(x: 10, y: 10, width: 300, height: 300))来创建它,但是由于某些原因,我不能使用约束来完成它。这是我在viewDidLoad()中调用的函数:

private func configureTextView() {
        view.addSubview(textView)
        textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10)
        textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10)
        textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10)
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10)
        textView.backgroundColor = .red
        print(view.subviews)
}

这是textView

private let textView: UITextView = {
        let view = UITextView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
}()

我还是一个初学者,但是print(view.subviews)表明textView是主视图的子视图(我想)

[<UITextView: 0x7fdf64809600; frame = (0 0; 0 0); text = '';
clipsToBounds = YES; gestureRecognizers = <NSArray: 0x60000062f450>;
layer = <CALayer: 0x60000083b360>; contentOffset: {0, 0}; contentSize:
{0, -8}; adjustedContentInset: {0, 0, 0, 0}>]

2 个答案:

答案 0 :(得分:3)

您创建约束,但不要将其设置为活动约束。对此进行更改应有助于使其正确显示:

textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10).isActive = true
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10).isActive = true

答案 1 :(得分:0)

您也可以使用“ SnapKit”

https://github.com/SnapKit/SnapKit

  

pod'SnapKit','〜> 5.0.0'

    self.addSubView(textView)
    textView.snp.makeConstraints { (make) -> Void in
           make.top.equalTo(0)
           make.bottom.equalTo(0)
           make.left.equalTo(0)
           make.right.equalTo(0)
    }