iOS/iOS SeSAC 2기 TIL

iOS UISwitch에 대한 UI 속성

Developer-Michelle 2022. 7. 6. 18:25

setOn(_:animated:)

Set the state of the switch to On or Off, optionally animating the transition.

func setOn( _ on: Bool, animated: Bool )

 

쓰임새 =

switchName.setOn(true, animated: true)

 

onTintColor

The color used to tint the appearance of the switch when it’s in the on position.

on 위치에 있을 때 스위치 모양의 색상 바꾸기

var onTintColor: UIColor? { get set }

 

thumbTintColor

The color used to tint the appearance of the thumb.

하얀 동그라미 색상 바꾸는거

var thumbTintColor: UIColor? { get set }

 

offColor 바꾸는 방법: stackoverflow 참고

let onColor  = _your_on_state_color
let offColor = _your_off_state_color

let mSwitch = UISwitch(frame: CGRect.zero)
mSwitch.on = true

/*For on state*/
mSwitch.onTintColor = onColor

/*For off state*/
mSwitch.tintColor = offColor
mSwitch.layer.cornerRadius = mSwitch.frame.height / 2.0
mSwitch.backgroundColor = offColor
mSwitch.clipsToBounds = true

-> 위에 코드대로 하면 안되어서 밑에 다른 사이트 참조해서 적용됨

 

tintColor는 빼도 되고

backgroundColor 와 cornerRadius이용해서 off일 때 색상 만든다.

layer는 디폴트가 네모라서 둥글게 깎음

 

밑에 루트뷰의 background가 default 라면 투명처럼 보이게 되어서

일단 background 색상을 정해주고, 디폴트가 네모이기 때문에 둥글게 깎는다.

 

 

https://iosrevisited.blogspot.com/2019/06/swift-uiswitch-color-in-on-off-change-height.html

 

Swift UISwitch color in On state & Off state, Change Switch height in swift - iOS

UISwitch in swift has two states either On or Off. This switches mostly see in native  settings app. First add switch to view as below, add following code in viewDidLoad() method: let switchButton = UISwitch() switchButton.translatesAutoresizingMaskIntoCo

iosrevisited.blogspot.com

 

 

과제 중 적용 예시

switchBtn.setOn(true, animated: true)

switchBtn.onTintColor = .red

switchBtn.thumbTintColor = .white