iOS

Swift 9 - 앱 개발하기

Jihyeonnn 2024. 11. 6. 16:50
개발 전 알고 시작해야 할 것!

- Outlet이 연결되어 있는 개체는 복사하면 안 된다.

- 기능은 Action, 변수는 Outlet으로 설정한다.

 

App Icon을 설정할 때에는, 

Assets.xcassests에 가서 AppIcon에 1024*1024 pixel의 이미지를 업로드해 주자!

image의 크기를 설정할 때는, Aspect Fit으로 종횡비가 흐트러지지 않게 채워지도록 설정해 주는 것이 좋다.

 

import UIKit

class ViewController: UIViewController {
    var x : Int = 0
    @IBOutlet weak var txtName: UITextField!
    @IBOutlet weak var lblhello: UILabel!
    @IBOutlet weak var lblNumber: UILabel!
    
    @IBAction func btnDown(_ sender: UIButton) {
        x = x - 1
        lblNumber.text = String(x)
    }
    @IBAction func btnUp(_ sender: UIButton) {
        x = x + 1
        lblNumber.text = String(x)
    }
    @IBAction func btnSend(_ sender: UIButton) {
        lblhello.text = "Hi, " + txtName.text!
        print(lblhello.text, txtName.text)
    }
    @IBAction func resetBtn(_ sender: UIButton) {
        lblhello.textColor = .systemYellow
        lblhello.text = "안녕하세요!"
        txtName.text = ""
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}

 

 

해당 소스 코드의 결과이다. 

+ 와 - 를 누를 때마다 S 레이블에 +1 추가된 숫자가 출력된다.

 

항상 맨 우측 창에 있는 Connetions Inspector를 잘 확인하자.

 

1. 기본 UILabel 설정 텍스트를 기본적으로 표시하는 예제입니다. text, textColor, font, textAlignment
2. 다중 줄 텍스트 여러 줄로 텍스트가 자동으로 감싸지도록 설정하는 예제입니다. numberOfLines, lineBreakMode
3. 자동 크기 조정 (Dynamic Type) 접근성 설정에 맞춰 텍스트 크기가 자동으로 조정되도록 설정합니다. `font = UIFont

 

위의 표는 UILabel의 다양한 사용 예시를 표로 정리한 것이다.

 

기타 앱 예제들이다. (출처 하단 표기)

//
//  ViewController.swift
//  ImageView
//
//  Created by Ho-Jeong Song on 2021/11/23.
//

import UIKit

// ViewController 클래스 정의
class ViewController: UIViewController {

    // 상태를 나타내는 변수 (이미지 확대/축소 여부)
    var isZoom = false
    
    // 이미지 상태를 저장할 변수 (전구 켜짐 이미지, 전구 꺼짐 이미지)
    var imgOn: UIImage?
    var imgOff: UIImage?

    // IBOutlet: 스토리보드에서 연결된 UIImageView와 UIButton을 참조
    @IBOutlet var imgView: UIImageView!  // 이미지 뷰
    @IBOutlet var btnResize: UIButton!   // 이미지 크기 변경 버튼
    
    // 화면이 로드된 후 호출되는 함수
    override func viewDidLoad() {
        super.viewDidLoad()
        // 뷰가 로드된 후 추가적인 설정을 할 수 있는 곳
        
        // 이미지 이름으로 UIImage 객체를 생성하여 변수에 할당
        imgOn = UIImage(named: "lamp_on.png")   // 전구 켜짐 이미지
        imgOff = UIImage(named: "lamp_off.png") // 전구 꺼짐 이미지
        
        // 초기 상태로 imgView의 이미지를 켜짐 상태로 설정
        imgView.image = imgOn
    }

    // 버튼을 클릭하여 이미지 크기를 확대/축소하는 함수
    @IBAction func btnResizeImage(_ sender: UIButton) {
        let scale: CGFloat = 2.0  // 확대/축소 비율 (2배 크기)
        var newWidth: CGFloat, newHeight: CGFloat

        // 이미지가 확대 상태인지 축소 상태인지를 확인
        if (isZoom) {   // true: 확대 상태
            // 이미지의 크기를 기존 크기의 반으로 설정 (축소)
            newWidth = imgView.frame.width / scale
            newHeight = imgView.frame.height / scale
            
            // 버튼의 제목을 "확대"로 변경
            btnResize.setTitle("확대", for: .normal)
        }
        else {  // false: 축소 상태
            // 이미지의 크기를 기존 크기의 두 배로 설정 (확대)
            newWidth = imgView.frame.width * scale
            newHeight = imgView.frame.height * scale
            
            // 버튼의 제목을 "축소"로 변경
            btnResize.setTitle("축소", for: .normal)
        }
        
        // 이미지 뷰의 크기를 새로운 크기로 설정
        imgView.frame.size = CGSize(width: newWidth, height: newHeight)
        
        // 확대/축소 상태를 반전시켜 isZoom 값 업데이트
        isZoom = !isZoom
    }
    
    // 스위치의 상태에 따라 이미지를 변경하는 함수
    @IBAction func switchImageOnOff(_ sender: UISwitch) {
        // 스위치가 켜져 있으면 imgOn(전구 켜짐 이미지)로 변경
        if sender.isOn {
            imgView.image = imgOn
        } else {  // 스위치가 꺼져 있으면 imgOff(전구 꺼짐 이미지)로 변경
            imgView.image = imgOff
        }
    }
}

 

 

인터넷에 있는 URL이나 HTML 보여 줄 때 사용하는 내장형 시스템인 웹 뷰다.

//
//  ViewController.swift
//  Web
//
//  Created by BeomGeun Lee on
//

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet var txtUrl: UITextField!
    @IBOutlet var myWebView: WKWebView!
    @IBOutlet var myActivityIndicator: UIActivityIndicatorView!
    
    func loadWebPage(_ url: String) {
        let myUrl = URL(string: url)
        let myRequest = URLRequest(url: myUrl!)
        myWebView.load(myRequest)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        myWebView.navigationDelegate = self
        loadWebPage("https://jihyeon-song.tistory.com/")
    }
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        myActivityIndicator.startAnimating()
        myActivityIndicator.isHidden = false
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        myActivityIndicator.stopAnimating()
        myActivityIndicator.isHidden = true
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        myActivityIndicator.stopAnimating()
        myActivityIndicator.isHidden = true
    }
    
    func checkUrl(_ url: String) -> String {
       var strUrl = url
        let flag = strUrl.hasPrefix("http://")
        if !flag {
            strUrl = "http://" + strUrl
        }
        return strUrl
    }

    @IBAction func btnGotoUrl(_ sender: UIButton) {
        let myUrl = checkUrl(txtUrl.text!)
        txtUrl.text = ""
        loadWebPage(myUrl)
    }
    
    @IBAction func btnGoSite1(_ sender: UIButton) {
        loadWebPage("http://op.gg")
    }
    
    @IBAction func btnGoSite2(_ sender: UIButton) {
        loadWebPage("http://youtube.com")
    }
    
    @IBAction func btnLoadHtmlString(_ sender: UIButton) {
        let htmlString = "<h1> HTML String </h1><p> String 변수를 이용한 Jihyeon's 웹페이지 </p> <p><a href=\"http://2sam.net\">2sam</a>으로 이동</p>"
        myWebView.loadHTMLString(htmlString, baseURL: nil)
    }
    
    @IBAction func btnLoadHtmlFile(_ sender: UIButton) {
        let filePath = Bundle.main.path(forResource: "htmlView", ofType: "html")
        let myUrl = URL(fileURLWithPath: filePath!)
        let myRequest = URLRequest(url: myUrl)
        myWebView.load(myRequest)
    }
    
    @IBAction func btnStop(_ sender: UIBarButtonItem) {
        myWebView.stopLoading()
    }
    
    @IBAction func btnReload(_ sender: UIBarButtonItem) {
        myWebView.reload()
    }
    
    @IBAction func btnGoBack(_ sender: UIBarButtonItem) {
        myWebView.goBack()
    }
    
    @IBAction func btnGoForward(_ sender: UIBarButtonItem) {
        myWebView.goForward()
    }
    
}

 

웹 뷰의 소스 코드이다.

Simulator의 Features -> Location에서 내 움직임을 설정할 수 있다.

한국폴리텍대학을 다른 대학으로 설정해 보겠다.

위도와 경도는 링크에서 확인할 수 있다. 

 

//
//  ViewController.swift
//  Map
//
//  Created by BeomGeun Lee on 2021
//

import UIKit
import MapKit

// ViewController 클래스 정의, CLLocationManagerDelegate 프로토콜 채택
class ViewController: UIViewController, CLLocationManagerDelegate {

    // 스토리보드에서 연결된 IBOutlet 변수들
    @IBOutlet var myMap: MKMapView!  // 지도 객체
    @IBOutlet var lblLocationInfo1: UILabel!  // 위치 정보 1
    @IBOutlet var lblLocationInfo2: UILabel!  // 위치 정보 2
    
    // CLLocationManager 객체 생성 (위치 관리용)
    let locationManager = CLLocationManager()
    
    // 뷰가 로드될 때 호출되는 메서드
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // UILabel 초기화 (위치 정보는 빈 문자열로 설정)
        lblLocationInfo1.text = ""
        lblLocationInfo2.text = ""
        
        // locationManager의 delegate를 현재 ViewController로 설정
        locationManager.delegate = self
        
        // 위치 정확도를 가장 높은 수준으로 설정
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        
        // 앱이 사용할 위치 권한을 요청
        locationManager.requestWhenInUseAuthorization()
        
        // 위치 업데이트 시작
        locationManager.startUpdatingLocation()
        
        // 지도에서 사용자의 현재 위치를 표시하도록 설정
        myMap.showsUserLocation = true
    }
    
    // 특정 위도, 경도로 지도를 이동시키는 메서드
    func goLocation(latitudeValue: CLLocationDegrees, longitudeValue : CLLocationDegrees, delta span :Double) -> CLLocationCoordinate2D {
        // 주어진 위도, 경도로 CLLocationCoordinate2D 객체 생성
        let pLocation = CLLocationCoordinate2DMake(latitudeValue, longitudeValue)
        
        // 지도 범위 설정 (줌 수준을 설정하는 데 사용)
        let spanValue = MKCoordinateSpan(latitudeDelta: span, longitudeDelta: span)
        
        // 지도에 표시할 지역 설정
        let pRegion = MKCoordinateRegion(center: pLocation, span: spanValue)
        
        // 지도를 설정된 영역으로 이동
        myMap.setRegion(pRegion, animated: true)
        
        // 현재 위치를 반환
        return pLocation
    }

    // 지도에 특정 위치에 주석을 추가하는 메서드
    func setAnnotation(latitudeValue: CLLocationDegrees, longitudeValue : CLLocationDegrees, delta span :Double, title strTitle: String, subtitle strSubtitle:String) {
        // MKPointAnnotation 객체 생성 (주석을 추가할 때 사용)
        let annotation = MKPointAnnotation()
        
        // 주석의 위치 설정
        annotation.coordinate = goLocation(latitudeValue: latitudeValue, longitudeValue: longitudeValue, delta: span)
        
        // 주석의 제목과 부제목 설정
        annotation.title = strTitle
        annotation.subtitle = strSubtitle
        
        // 지도에 주석 추가
        myMap.addAnnotation(annotation)
    }
    
    // 위치 업데이트가 완료되면 호출되는 메서드
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // 최신 위치 정보를 받아옴
        let pLocation = locations.last
        
        // 지도에 해당 위치로 이동
        _ = goLocation(latitudeValue: (pLocation?.coordinate.latitude)!, longitudeValue: (pLocation?.coordinate.longitude)!, delta: 0.01)
        
        // 위치 정보를 역 지오코딩 (위도, 경도를 주소로 변환)
        CLGeocoder().reverseGeocodeLocation(pLocation!, completionHandler: {
            (placemarks, error) -> Void in
            // 역 지오코딩 결과에서 첫 번째 플래스마크 정보 가져오기
            let pm = placemarks!.first
            
            // 국가 정보 추출
            let country = pm!.country
            var address: String = country!
            
            // 지역(locality) 정보가 있으면 주소에 추가
            if pm!.locality != nil {
                address += " "
                address += pm!.locality!
            }
            
            // 거리(thoroughfare) 정보가 있으면 주소에 추가
            if pm!.thoroughfare != nil {
                address += " "
                address += pm!.thoroughfare!
            }
            
            // 주소 정보를 UILabel에 표시
            self.lblLocationInfo1.text = "현재 위치"
            self.lblLocationInfo2.text = address
        })
        
        // 위치 업데이트를 중지 (최초 위치만 사용할 경우)
        locationManager.stopUpdatingLocation()
    }

    // UISegmentedControl의 선택된 세그먼트에 따라 다른 위치를 표시하는 메서드
    @IBAction func sgChangeLocation(_ sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == 0 {
            // 첫 번째 세그먼트 (현재 위치 선택)
            self.lblLocationInfo1.text = ""
            self.lblLocationInfo2.text = ""
            
            // 위치 업데이트 시작
            locationManager.startUpdatingLocation()
        } else if sender.selectedSegmentIndex == 1 {
            // 두 번째 세그먼트 (인덕대학 위치 선택)
            setAnnotation(latitudeValue: 37.6314191, longitudeValue: 127.0548249, delta: 1, title: "인덕대학", subtitle: "노원구 월계동")
            
            // 위치 정보 업데이트
            self.lblLocationInfo1.text = "보고 계신 위치"
            self.lblLocationInfo2.text = "한국폴리텍대학 강릉캠퍼스"
        } else if sender.selectedSegmentIndex == 2 {
            // 세 번째 세그먼트 (이지스퍼블리싱 위치 선택)
            setAnnotation(latitudeValue: 37.556876, longitudeValue: 126.914066, delta: 0.1, title: "이지스퍼블리싱", subtitle: "서울시 마포구 잔다리로 109 이지스 빌딩")
            
            // 위치 정보 업데이트
            self.lblLocationInfo1.text = "보고 계신 위치"
            self.lblLocationInfo2.text = "이지스퍼블리싱 출판사 "
        }
    }
}

 

수정한 코드이다. 실행한 후 features -> Custom location 에서 위도와 경도가 바뀌었는지 확인 후 OK.

= 위치가 원하는 곳으로 바뀐 것을 확인할 수 있다!

 

import UIKit

class ViewController: UIViewController {

    // 배경색이 바뀌는 타이머를 위한 변수
    var colorChangeTimer: Timer?
    
    // 배경색 변경을 위한 색상 배열
    let colors: [UIColor] = [.red, .green, .blue, .yellow, .orange, .purple, .cyan]
    
    // 배경색을 변경하는 메서드
    @objc func changeBackgroundColor() {
        // 색상 배열에서 무작위로 색상 하나를 선택
        let randomColor = colors.randomElement()!
        
        // 선택된 색상으로 배경색 변경
        self.view.backgroundColor = randomColor
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 뷰가 로드되면 타이머 시작 (1초마다 changeBackgroundColor 호출)
        colorChangeTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(changeBackgroundColor), userInfo: nil, repeats: true)
    }
    
    // 앱이 종료될 때 타이머를 무효화하는 메서드 (메모리 누수 방지)
    deinit {
        colorChangeTimer?.invalidate()
    }
}

 

추가로 GPT를 사용해 만들어 본 Lamp 앱이다.


 

 

출처: Smail Han의 iOS 프로그래밍 기초

Do it! 스위프트로 아이폰 앱 만들기 입문, 송호정, 이범근 저,이지스퍼블리싱, 2023년 01월 20일https://www.yes24.com/Product/Goods/116918114

https://github.com/doitswift/example


02 Hello World 앱 만들며 Xcode에 완벽 적응하기
03 원하는 이미지 화면에 출력하기 - 이미지 뷰
04 데이트 피커 사용해 날짜 선택하기
05 피커 뷰 사용해 원하는 항목 선택하기
06 얼럿 사용해 경고 표시하기
07 웹 뷰로 간단한 웹 브라우저 만들기
08 맵 뷰로 지도 나타내기
09 페이지 이동하기 - 페이지 컨트롤
10 탭 바 컨트롤러 이용해 여러 개의 뷰 넣기
11 내비게이션 컨트롤러 이용해 화면 전환하기
12 테이블 뷰 컨트롤러 이용해 할 일 목록 만들기
13 음악 재생하고 녹음하기
14 비디오 재생 앱 만들기
15 카메라와 포토 라이브러리에서 미디어 가져오기
16 코어 그래픽스로 화면에 그림 그리기
17 탭과 터치 사용해 스케치 앱 만들기
18 스와이프 제스처 사용하기
19 핀치 제스처 사용해 사진을 확대/축소하기