Lucas
Lucas

Reputation: 173

Left-aligning vertical UILabel in Swift

I'm working inside a UICollectionViewCell, trying to get a rotated UILabel to stick to the left of the label at a fixed width. This is what I have been able achieve:

Screenshot

As you can see, the label's dimensions seem relative to the length of the text and disabling auto-resizing has no effect. I would like to constrain the label to ~80 and occupy the full height of the cell, enough for the font with some spacing. The entire code for the 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")
    }
}

The ViewController sizeForItem returns the view width with 180 height. It does not play with anything of the cell, only setting the label's text.

I am still relatively new to iOS but have spent the past hour tinkering with this and just cannot get it to play nice! SnapKit is imported but I have had no success with it either. Is there some autosizing going on I'm not aware of? Any help would be greatly appreciated!

Upvotes: 0

Views: 391

Answers (1)

Arun Balakrishnan
Arun Balakrishnan

Reputation: 1502

I guess there is an issue with the constraints applied using anchors. As all the bottom anchor is also applied, the anchor point is different for different texts. I managed get a decent alignment by applying translating the position again by doing

 let transform = CGAffineTransform(rotationAngle: -.pi / 2).translatedBy(x: -25, y: -50)
categoryLabel.transform = transform

enter image description here

Constraints applied to the category label was aligned to leftAnchor, topAnchor and with a width of 100.

Upvotes: 2

Related Questions