如何使UITextView锚定到UICollectionViewCell的右边?

问题描述 投票:0回答:1

我有UITextView,我想将其锚定在UICollectionViewCell的右侧。我应用了以下约束:textView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true但是它并不能一直固定在右边。然后我应用以下约束,但是这次:textView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true并且确实将锚定到了最左边。为什么会这样呢?

https://imgur.com/a/uykWLw5

这是我的ChatMessageCell。

import UIKit

class ChatMessageCell: UICollectionViewCell {

    let textView: UITextView = {
        let tv = UITextView()
        tv.text = "Some Text"
        tv.font = UIFont.systemFont(ofSize: 16)
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()

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

        addSubview(textView)

        textView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        textView.widthAnchor.constraint(equalToConstant: 200).isActive = true
        textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
ios swift xcode uicollectionviewcell
1个回答
0
投票

您的textView将左对齐。如果要使文本视图保持200的宽度并显示在右侧,则需要添加:textView.textAlignment = .right

此外,我相信最好使用前导约束和尾随约束

© www.soinside.com 2019 - 2024. All rights reserved.