Deepti Raghav
Deepti Raghav

Reputation: 902

rotating button titleLabel text

I want title on a button to looks like:

enter image description here

What I have done so far -in my table view cell- is:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell  = tableView.dequeueReusableCell(withIdentifier: "CellJob") as!JobPostTbleCell
     cell.btnApply.titleLabel?.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
    cell.btnApply.titleLabel?.backgroundColor = UIColor.lightGray
    return cell

}

and I am getting this:

enter image description here

How to achieve the required output?

Upvotes: 1

Views: 476

Answers (4)

Deepti Raghav
Deepti Raghav

Reputation: 902

I added this code in cellForRowAt indexPath

 cell.btnApply.titleLabel?.transform = CGAffineTransform(rotationAngle: -(CGFloat.pi / 2))
    cell.btnApply.titleLabel?.textAlignment = .center
    cell.btnApply.titleLabel!.numberOfLines = 1

and change alignment of button from storyboard like this and it worked.

enter image description here

Upvotes: 2

Ahmad F
Ahmad F

Reputation: 31645

Consider that we have the following button:

enter image description here

As you can see, the width of the button is smaller than the title label width, but that's won't be applicable when rotating the height, it should appears with fully width (the height of the button is more than the label with even after rotating it).

By applying the following code:

myBtn.titleLabel?.transform = CGAffineTransform(rotationAngle: -(CGFloat.pi / 2))
myBtn.titleLabel!.numberOfLines = 0
myBtn.titleLabel!.adjustsFontSizeToFitWidth = true

The output would be:

enter image description here

Since my button is not in a table view cell, I implemented the above code in the viewDidLoad() method, which should also gives the desired output for a button in a cell...

Upvotes: 1

SPatel
SPatel

Reputation: 4946

Set custom class for your button "RotatableButton"

@IBDesignable class RotatableButton: UIButton {
    @IBInspectable var angle:CGFloat = 0 {
        willSet {
            rotate(angle: newValue)
        }
    }
    func rotate(angle: CGFloat) {
        let radians = angle / 180.0 * CGFloat.pi
        let rotation = self.transform.rotated(by: radians)
        self.titleLabel?.transform = rotation
    }
}

Upvotes: 1

TechBee
TechBee

Reputation: 1941

Try this:

cell.btnApply.titleLabel?.transform = view.transform.rotated(by: .pi)

Upvotes: 0

Related Questions