UILabel右锚不使用滚动视图swift

时间:2017-12-10 10:06:08

标签: ios swift uiscrollview uilabel constraints

我在故事板中创建了一个滚动视图。我在scrollView中以编程方式添加了UIlabel。我将UiLabel的正确锚点设置为滚动视图的右锚点,但它似乎无法正常工作。

问题是什么,或者我错过了什么。请帮忙

这是我的代码的一部分

@IBOutlet var scrollView: UIScrollView!    

override func viewDidLoad() {
    super.viewDidLoad()
    var lastBottomAnchor = self.scrollView.topAnchor
    for vocab in self.vocabularies {
        // Index
        let indexLabel = UILabel()
        indexLabel.text = vocab["index"] as? String
        indexLabel.font = UIFont.systemFont(ofSize: 14)
        indexLabel.translatesAutoresizingMaskIntoConstraints = false

        self.scrollView.addSubview(indexLabel)
        indexLabel.topAnchor.constraint(equalTo: lastBottomAnchor).isActive = true
        indexLabel.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor, constant: 8).isActive = true
        indexLabel.widthAnchor.constraint(equalToConstant: 40).isActive = true

        // Meaning
        let meaningLabel = UILabel()
        meaningLabel.text = "意味:\(vocab["english"]!)/\(vocab["vietnamese"]!)"
        meaningLabel.numberOfLines = 0
        meaningLabel.font = UIFont.systemFont(ofSize: 12)
        meaningLabel.layer.borderWidth = 0

        meaningLabel.translatesAutoresizingMaskIntoConstraints = false
        self.scrollView.addSubview(meaningLabel)
        meaningLabel.topAnchor.constraint(equalTo: indexLabel.bottomAnchor, constant: 8).isActive = true
        meaningLabel.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor, constant: 8).isActive = true
        meaningLabel.rightAnchor.constraint(equalTo: self.scrollView.rightAnchor, constant: -8).isActive = true

        // Set last item bottom constraint
        lastBottomAnchor = meaningLabel.bottomAnchor            

    }   
}

这是滚动视图的约束 enter image description here 这是我得到的(我不希望它可以横向滚动) enter image description here

这是我想要的东西 enter image description here

抱歉因为我的英语不好

2 个答案:

答案 0 :(得分:1)

我认为这是因为您没有为meaningLabel定义宽度约束,因此滚动视图会根据标签显示的文本长度保持水平滚动。

一旦定义了约束(假设meaningLabel.numberOfLines设置为0),文本就应该被包装:

meaningLabel.widthAnchor.constraint(equalTo: self.scrollView.widthAnchor, constant: -16).isActive = true

答案 1 :(得分:0)

您可以锁定水平滚动,限制滚动视图的内容大小,这样做:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.scrollView.contentSize = self.view.frame.size
}