ios - Swift 中的左对齐垂直 UILabel

标签 ios swift alignment uilabel snapkit

我在 UICollectionViewCell 内部工作,试图让旋转的 UILabel 以固定宽度粘在标签的左侧。这是我能够实现的:

Screenshot

如您所见,标签的尺寸似乎与文本的长度有关,禁用自动调整大小没有任何效果。我想将标签限制在 ~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

enter image description here

应用于类别标签的约束与 leftAnchor、topAnchor 对齐且宽度为 100。

关于ios - Swift 中的左对齐垂直 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472212/

相关文章:

image - Vuetify v-img 在 v-col 内对齐

android - Toast 中的文本居中

ios - 在已经在其他地方分配/初始化之后,如何从 XIB 重新加载 View ?

ios - UI 导航栏白色 Blob 外观

ios - 如何在不丢失格式的情况下将字符串转换为日期

swift - 单击事件 NSTextField OSX

swift - Xcode 12 和 iOS 14 中的手势问题

css - 如何让表格单元格右对齐?

xcode - iOS:popViewController 意外行为

iphone - 自动布局困惑 : Constraints for ScrollView with WebView and Header/Footer Views