如何正确包装长文本?

在我的应用程序中,用户可以在帖子中发表评论。一切正常,但是在创建长文本时线条不会换行,所以我明白了

如何正确包装长文本?

numberOfLines设置为= 0

这是commentCell中设置约束的代码


   let commentLabel: activeLabel = {
            let label = activeLabel()
            label.font = UIFont.systemFont(ofSize: 13)
            label.numberOfLines = 0

            return label
            }()

  override init(frame: CGRect) {
            super.init(frame: frame)



            addSubview(profileImageView)
            profileImageView.anchor(top: topAnchor,left: leftAnchor,bottom: nil,right: nil,paddingTop: 8,paddingLeft: 8,paddingBottom: 0,paddingRight: 0,width: 40,height: 40)
            profileImageView.layer.cornerRadius = 40 / 2


            addSubview(optionsButton)
            optionsButton.anchor(top: topAnchor,left: nil,right: rightAnchor,paddingTop: 12,paddingLeft: 0,paddingRight: 8,width: 20,height: 20)

            addSubview(commentLabel)
            commentLabel.anchor(top: topAnchor,left: profileImageView.rightAnchor,bottom: bottomAnchor,right: optionsButton.leftAnchor,paddingTop: 15,paddingLeft: 5,paddingBottom: 15,width: 0,height: 0)

            addSubview(commentTimeLabel)
        commentTimeLabel.anchor(top: commentLabel.bottomAnchor,left: commentLabel.leftAnchor,paddingTop: 3,paddingLeft: 1,height: 0)



            optionsButton.isEnabled = true

            optionsButton.isUserInteractionEnabled = true

            commentLabel.isUserInteractionEnabled = true
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

这是CommentViewController代码,应该为我调整单元格的大小,但不是。我以前曾经使用过它,所以不确定是否丢失了任何东西


   func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {


           let frame = CGRect(x: 0,y: 0,width: view.frame.width,height: 50)
           let dummyCell = CommentCell(frame: frame)
           dummyCell.comment = comments[indexPath.item]
           dummyCell.layoutIfNeeded()

           let targetSize = CGSize(width: view.frame.width,height: 1000)
           let estimatedSize = dummyCell.systemLayoutSizeFitting(targetSize)

           let height = max(40 + 8 + 8,estimatedSize.height)
           return CGSize(width: view.frame.width,height: height)
    }


    func collectionView(_ collectionView: UICollectionView,minimumLinespacingForSectionAt section: Int) -> CGFloat {
        return 15
    }


liping0207 回答:如何正确包装长文本?

您需要设置

commentLabel.lineBreakMode = .byWordWrapping

默认情况下,它设置为.byTruncatingTail

如果要将文本限制为一定行数,还可能需要设置.numberOfLines

,

numberOfLines = 0表示任何数字。线数 检查您是否对标签应用了适当的约束(高度和宽度),然后尝试再次查看结果

,

重新审视此问题后,问题出在我的约束下。

commentLabel.anchor

我将其更改为

bottom: commentTimeLabel.topAnchor

optionsButton.anchor

将底部更改为

 bottom: bottomAnchor
本文链接:https://www.f2er.com/3163107.html

大家都在问