Rotate UIView around its center keeping its size

前端 未结 10 1157
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 14:17

I\'m trying to rotate an UIView a few radians but after applying the transformation it doesn\'t look to be keeping its size. What\'s the proper way to achieve t

10条回答
  •  旧时难觅i
    2020-12-02 14:35

    Swift + extension are your friends!

    // MARK: - UIView Extension -
    
    extension UIView {
    
        /**
         Rotate a view by specified degrees
    
         - parameter angle: angle in degrees
         */
        func rotate(angle: CGFloat) {
            let radians = angle / 180.0 * CGFloat.pi
            let rotation = CGAffineTransformRotate(self.transform, radians);
            self.transform = rotation
        }
    
    }
    

    In this way, anywhere in your code:

    let view = UIView(frame: CGRectMake(0, 0, 100, 100))
    view.backgroundColor = UIcolor.redColor()
    view.rotate(angle: 90)
    

提交回复
热议问题