カテゴリー
iOS Swift

UIViewをsubviewごとRotateしたい

sample code

square.transform = CGAffineTransformMakeRotation(CGFloat.pi/2) のようにすると可能

import UIKit

class ViewController: UIViewController {
  
  var viewWidth: CGFloat {
    return view.bounds.width
  }
  
  var viewHeight: CGFloat {
    return view.bounds.height
  }

  lazy var square: UIView = {
    let view = UIView()
    view.backgroundColor = .red
    return view
  }()
  
  lazy var smallSquare: UIView = {
    let view = UIView()
    view.backgroundColor = .blue
    return view
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    
    view.addSubview(square)
    square.addSubview(smallSquare)
  }
  
  override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    layout()
  }
  
  private func layout() {
    let squareWidth: CGFloat = 300
    let squareHeight: CGFloat = 200
    
    let innerSquareWidth: CGFloat = 250
    let innerSquareHeight: CGFloat = 150
    
    square.frame = CGRect(x: viewWidth/2 - squareWidth/2, y: viewHeight/2 - squareHeight/2, width: squareWidth, height: squareHeight)
    smallSquare.frame = CGRect(x: square.bounds.width/2 - innerSquareWidth/2, y: square.bounds.height/2 - innerSquareHeight/2, width: innerSquareWidth, height: innerSquareHeight)
    
    square.transform = CGAffineTransformMakeRotation(CGFloat.pi/2)
  }
}