问题
I am trying to change the default height and width of a UISwitch element in iOS, but unsuccessfully.
Can you change the default height and width of a UISwitch element?
Should the element be created programmatically?
回答1:
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];
回答2:
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.
回答3:
Swift 4
@IBOutlet weak var switchDemo: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchDemo.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
}
回答4:
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()
}
}
回答5:
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)
}
}
来源:https://stackoverflow.com/questions/25104605/changing-uiswitch-width-and-height