기능
- 버튼(확대, 축소)를 누를 시 전구가 확대되거나 축소된다.
- 현재 확대 되어있는 상태라면 버튼이
축소
로 되고, 축소 되어 있는 상태라면 버튼이 확대
로 된다.
- 스위치를 끄면 전구가 꺼지며, 스위치를 키면 전구가 켜진다.
코드
import UIKit
class ViewController: UIViewController {
var isZoom = false
var imgOn: UIImage?
var imgOff: UIImage?
@IBOutlet var imgView: UIImageView!
@IBOutlet var resizeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
imgOn = UIImage(named: "lamp_on")
imgOff = UIImage(named: "lamp_off")
imgView.image = imgOn
}
@IBAction func touchUpResizeButton(_ sender: UIButton) {
let scale: CGFloat = 2.0
var newWidth : CGFloat
var newHeight: CGFloat
if isZoom {
resizeButton.setTitle("확대", for: .normal)
newWidth = imgView.frame.width / scale
newHeight = imgView.frame.height / scale
}else{
resizeButton.setTitle("축소", for: .normal)
newWidth = imgView.frame.width * scale
newHeight = imgView.frame.height * scale
}
isZoom.toggle()
imgView.frame.size = CGSize(width: newWidth, height: newHeight)
}
@IBAction func switchOnOffButton(_ sender: UISwitch){
if sender.isOn{
imgView.image = imgOn
}else{
imgView.image = imgOff
}
}
}
- 어플리케이션이 시작할 때, 이미지파일을 이미지 변수에 둔다.
- 버튼이 눌릴시 현재 상태(확대되어 있는지)에 따라 크기를 2배 늘리거나 줄인다.
CGFloat
형 높이 변수와 넓이 변수를 크기에 따라 조절한 뒤, CGSize()
메소드에 넣어 줌으로써 이미지의 크기를 변경한다.