如何使UILabel动态?

时间:2019-07-06 21:22:59

标签: ios swift

如何根据给它的注释文本使UIlabel包装多少次?

我尝试了很多类似的事情:

        self.commentText.contentMode = .scaleToFill
    self.commentText.numberOfLines = 0
//        self.commentText.leadingMargin(pixel: 10)
//        self.commentText.trailingMargin(pixel: 10)

我来自 [Qs like。]和UILabel - auto-size label to fit text? 1

但是无法使包装工作

我如何设置:

        private func setupTheCommentText() {
        self.commentText.frame = CGRect(x: 85, y: 35, width: 272, height: 15)
        self.commentText.textColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1)
        self.commentText.font = UIFont(name: "SFCompactDisplay-Medium", size: 13)
        //self.commentText.numberOfLines = 0
        //self.commentText.contentMode = .scaleAspectFill
        //self.commentText.translatesAutoresizingMaskIntoConstraints = false
//        self.commentText.leadingMargin(pixel: 10)
//        self.commentText.trailingMargin(pixel: 10)
        self.addSubview(commentText)
        self.commentText.topAnchor.constraint(equalTo:username.bottomAnchor).isActive = true
        commentText.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            self.commentText.topAnchor.constraint(equalTo:username.bottomAnchor),
            self.commentText.leadingAnchor.constraint(equalTo:self.contentView.leadingAnchor,constant:85.0),
            self.commentText.trailingAnchor.constraint(equalTo:self.contentView.trailingAnchor,constant:-15.0),//,constant:-85.0
            self.commentText.bottomAnchor.constraint(equalTo:commentText.bottomAnchor)
            ])
    }

1 个答案:

答案 0 :(得分:1)

赋予这些约束

  

leading,trailing,top,bottom //底部是单元格

commentText.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
  self.commentText.topAnchor.constraint(equalTo:username.bottomAnchor),
  self.commentText.leadingAnchor.constraint(equalTo:self.view.leadingAnchor,constant:85.0),
  self.commentText.trailingAnchor.constraint(equalTo:self.view.trailingAnchor,constant:-85.0),
  self.commentText.bottomAnchor.constraint(equalTo:self.view.bottomAnchor) // this for cells 
])

在上述情况下,我假设它位于vc的视图内,如果不是这种情况,并且是单元格,则将self.view替换为self.contentView