我有UITextView,我想将其锚定在UICollectionViewCell的右侧。我应用了以下约束:textView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
但是它并不能一直固定在右边。然后我应用以下约束,但是这次:textView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
并且确实将锚定到了最左边。为什么会这样呢?
这是我的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")
}
}
您的textView将左对齐。如果要使文本视图保持200的宽度并显示在右侧,则需要添加:textView.textAlignment = .right
此外,我相信最好使用前导约束和尾随约束