我在 UICollectionViewCell 内部工作,试图让旋转的 UILabel 以固定宽度粘在标签的左侧。这是我能够实现的:
如您所见,标签的尺寸似乎与文本的长度有关,禁用自动调整大小没有任何效果。我想将标签限制在 ~80 并占据单元格的整个高度,足以让字体有一定的间距。 UICollectionViewCell 的完整代码:
import Foundation
import UIKit
class DayOfWeekCell: UICollectionViewCell {
let categoryLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .red
categoryLabel.transform = CGAffineTransform.init(rotationAngle: -CGFloat.pi/2)
categoryLabel.textColor = UIColor.white
categoryLabel.font = UIFont.systemFont(ofSize: 25)
categoryLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(categoryLabel)
categoryLabel.backgroundColor = .blue
categoryLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
categoryLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
categoryLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
ViewController sizeForItem 返回 180 高度的 View 宽度。它不处理单元格的任何内容,只设置标签的文本。
我对 iOS 还是比较陌生,但在过去的一个小时里一直在修改它,但就是无法让它发挥得很好! SnapKit 是进口的,但我也没有成功。是否有一些我不知道的自动调整大小?任何帮助将不胜感激!
最佳答案
我猜想使用 anchor 应用的约束存在问题。由于也应用了所有底部 anchor ,因此不同文本的 anchor 是不同的。我设法通过再次应用翻译位置来获得良好的对齐
let transform = CGAffineTransform(rotationAngle: -.pi / 2).translatedBy(x: -25, y: -50)
categoryLabel.transform = transform
应用于类别标签的约束与 leftAnchor、topAnchor 对齐且宽度为 100。
关于ios - Swift 中的左对齐垂直 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472212/