Changing UISwitch width and height

两盒软妹~` 提交于 2019-12-03 01:21:28
William George

I tested the theory and it appears that you can use a scale transform to increase the size of the UISwitch

UISwitch *aSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(120, 120, 51, 31)];
aSwitch.transform = CGAffineTransformMakeScale(2.0, 2.0);
[self.view addSubview:aSwitch];

Not possible. A UISwitch has a locked intrinsic height of 51 x 31 .

You can force constraints on the switch at design time in the xib...

but come runtime it will snap back to its intrinsic size.

You can supply another image via the .onImage / .offImage properties but again from the docs.

The size of this image must be less than or equal to 77 points wide and 27 points tall. If you specify larger images, the edges may be clipped.

You are going to have to bake your own custom one if you want another size.

Swift 4

@IBOutlet weak var switchDemo: UISwitch!

override func viewDidLoad() {
    super.viewDidLoad()
   switchDemo.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
}

here is a nice UISwitch subclass that i wrote for this purpose, its also IBDesignable so you can control it from your Storyboard / xib

@IBDesignable class BigSwitch: UISwitch {

    @IBInspectable var scale : CGFloat = 1{
        didSet{
            setup()
        }
    }

    //from storyboard
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    //from code
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    private func setup(){
        self.transform = CGAffineTransform(scaleX: scale, y: scale)
    }

    override func prepareForInterfaceBuilder() {
        setup()
        super.prepareForInterfaceBuilder()
    }


}

Swift 5:

import UIKit

extension UISwitch {

    func set(width: CGFloat, height: CGFloat) {

        let standardHeight: CGFloat = 31
        let standardWidth: CGFloat = 51

        let heightRatio = height / standardHeight
        let widthRatio = width / standardWidth

        transform = CGAffineTransform(scaleX: widthRatio, y: heightRatio)
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!