iOS 프로그래밍 10주차

2024. 11. 6. 16:48📱 모바일 프로그래밍/iOS 프로그래밍 기초

 

is Initial View Controller

 

AppIcon

 

LaunchScreen

 

.textColor

 

iOS UILable

1. 기본 UILabel 생성 및 설정

let label = UILabel()
label.text = "Hello, World!"
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 18)
label.textAlignment = .center

2. 동적으로 레이블 크기 조정

label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping

3. 속성 텍스트 사용하기

let attributedString = NSMutableAttributedString(string: "Bold and Italic Text")
attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSRange(location: 0, length: 4))
attributedString.addAttribute(.font, value: UIFont.italicSystemFont(ofSize: 18), range: NSRange(location: 9, length: 6))
label.attributedText = attributedString

4. 그림자 효과 적용

label.layer.shadowColor = UIColor.gray.cgColor
label.layer.shadowOffset = CGSize(width: 2, height: 2)
label.layer.shadowOpacity = 0.7
label.layer.shadowRadius = 2

 

Content Mode - Aspect Fill

 

+, -

import UIKit

class ViewController: UIViewController {
    var x : Int = 0
    @IBOutlet weak var lblNumber: UILabel!
    
    @IBOutlet weak var lblHello: UILabel!
    @IBOutlet weak var txtName: UITextField!
    @IBAction func btnUp(_ sender: UIButton) {
        x = x + 1
        lblNumber.text = String(x)
    }
    
    @IBAction func btnDown(_ 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 = .white
        lblHello.text = "안녕하세요"
        txtName.text = ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}

변화가 있으면 outlet

기능이면 action

 

Main.stroyboard - ViewController - connections inspector

 

 

03 원하는 이미지 화면에 출력하기 - 이미지 뷰

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

import UIKit // UIKit 프레임워크를 임포트하여 UI 구성 요소를 사용할 수 있도록 함

// ViewController 클래스 정의, UIViewController를 상속받음
class ViewController: UIViewController {
    var isZoom = false // 이미지 확대/축소 상태를 저장하는 변수
    var imgOn: UIImage? // "켜짐" 상태의 이미지를 저장할 변수
    var imgOff: UIImage? // "꺼짐" 상태의 이미지를 저장할 변수

    @IBOutlet var imgView: UIImageView! // 스토리보드에서 연결된 UIImageView 아울렛
    @IBOutlet var btnResize: UIButton! // 스토리보드에서 연결된 UIButton 아울렛
    
    // 뷰가 로드된 후 호출되는 메서드
    override func viewDidLoad() {
        super.viewDidLoad() // 부모 클래스의 viewDidLoad 호출

        // 이미지 파일을 로드하여 변수에 저장
        imgOn = UIImage(named: "lamp_on.png")
        imgOff = UIImage(named: "lamp_off.png")
        
        imgView.image = imgOn // 초기 이미지로 "켜짐" 상태의 이미지 설정
    }

    // 버튼 클릭 시 호출되는 메서드
    @IBAction func btnResizeImage(_ sender: UIButton) {
        let scale: CGFloat = 2.0 // 확대/축소 비율 설정
        var newWidth: CGFloat, newHeight: CGFloat // 새로운 너비와 높이를 저장할 변수 선언

        if (isZoom) {   // 현재 상태가 확대일 경우
            newWidth = imgView.frame.width / scale // 너비를 축소 비율로 나눔
            newHeight = imgView.frame.height / scale // 높이를 축소 비율로 나눔
            
            btnResize.setTitle("확대", for: .normal) // 버튼 제목을 "확대"로 변경
        }
        else {  // 현재 상태가 축소일 경우
            newWidth = imgView.frame.width * scale // 너비를 확대 비율로 곱함
            newHeight = imgView.frame.height * scale // 높이를 확대 비율로 곱함
            
            btnResize.setTitle("축소", for: .normal) // 버튼 제목을 "축소"로 변경
        }
        
        imgView.frame.size = CGSize(width: newWidth, height: newHeight) // 이미지 뷰의 크기를 새로운 크기로 설정
        
        isZoom = !isZoom // 확대/축소 상태를 반전시킴
    }
    
    // 스위치 상태 변화 시 호출되는 메서드
    @IBAction func switchImageOnOff(_ sender: UISwitch) {
        if sender.isOn { // 스위치가 켜져 있을 경우
            imgView.image = imgOn // 이미지 뷰에 "켜짐" 상태의 이미지 설정
        } else { // 스위치가 꺼져 있을 경우
            imgView.image = imgOff // 이미지 뷰에 "꺼짐" 상태의 이미지 설정
        }
    }
}

 

04 데이트 피커 사용해 날짜 선택하기

 

05

 

06

 

07

웹뷰: 

내장형 웹 브라우저

 

08

 

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

import UIKit // UIKit 프레임워크를 임포트하여 UI 구성 요소를 사용할 수 있도록 함
import MapKit // MapKit 프레임워크를 임포트하여 지도 관련 기능 사용

// ViewController 클래스 정의, UIViewController를 상속받고 CLLocationManagerDelegate 프로토콜을 채택
class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var myMap: MKMapView! // 스토리보드에서 연결된 MKMapView 아울렛
    @IBOutlet var lblLocationInfo1: UILabel! // 스토리보드에서 연결된 UILabel 아울렛 (위치 정보 1)
    @IBOutlet var lblLocationInfo2: UILabel! // 스토리보드에서 연결된 UILabel 아울렛 (위치 정보 2)
    
    let locationManager = CLLocationManager() // 위치 관리 객체 생성
    
    // 뷰가 로드된 후 호출되는 메서드
    override func viewDidLoad() {
        super.viewDidLoad() // 부모 클래스의 viewDidLoad 호출
        // 추가적인 설정을 위해 초기화
        lblLocationInfo1.text = "" // 위치 정보 1 초기화
        lblLocationInfo2.text = "" // 위치 정보 2 초기화
        locationManager.delegate = self // 위치 관리자의 delegate를 현재 ViewController로 설정
        locationManager.desiredAccuracy = kCLLocationAccuracyBest // 위치 정확도 설정
        locationManager.requestWhenInUseAuthorization() // 앱 사용 중 위치 권한 요청
        locationManager.startUpdatingLocation() // 위치 업데이트 시작
        myMap.showsUserLocation = true // 사용자 위치를 지도에 표시
    }
    
    // 주어진 위도, 경도로 지도를 이동시키는 메서드
    func goLocation(latitudeValue: CLLocationDegrees, longitudeValue: CLLocationDegrees, delta span: Double) -> CLLocationCoordinate2D {
        let pLocation = CLLocationCoordinate2DMake(latitudeValue, longitudeValue) // CLLocationCoordinate2D 객체 생성
        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) {
        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! // 주소 초기화
            if pm!.locality != nil { // 지역 정보가 있을 경우
                address += " "
                address += pm!.locality! // 지역 이름 추가
            }
            if pm!.thoroughfare != nil { // 도로 정보가 있을 경우
                address += " "
                address += pm!.thoroughfare! // 도로 이름 추가
            }
            
            self.lblLocationInfo1.text = "현재 위치" // 위치 정보 레이블 1에 텍스트 설정
            self.lblLocationInfo2.text = address // 위치 정보 레이블 2에 주소 설정
            })
        
        locationManager.stopUpdatingLocation() // 위치 업데이트 중지
    }

    // 세그먼트 컨트롤 변경 시 호출되는 메서드
    @IBAction func sgChangeLocation(_ sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == 0 { // 첫 번째 세그먼트 선택 시
            self.lblLocationInfo1.text = "" // 위치 정보 1 초기화
            self.lblLocationInfo2.text = "" // 위치 정보 2 초기화
            locationManager.startUpdatingLocation() // 위치 업데이트 시작
        } else if sender.selectedSegmentIndex == 1 { // 두 번째 세그먼트 선택 시
            setAnnotation(latitudeValue: 37.6314191, longitudeValue: 127.0548249, delta: 1, title: "인덕대학교", subtitle: "노원구 월계동") // 인덕대학교 주석 추가
            self.lblLocationInfo1.text = "보고 계신 위치" // 위치 정보 레이블 1에 텍스트 설정
            self.lblLocationInfo2.text = "인덕대학교" // 위치 정보 레이블 2에 텍스트 설정
        } else if sender.selectedSegmentIndex == 2 { // 세 번째 세그먼트 선택 시
            setAnnotation(latitudeValue: 37.556876, longitudeValue: 126.914066, delta: 0.1, title: "이지스퍼블리싱", subtitle: "서울시 마포구 잔다리로 109 이지스 빌딩") // 이지스퍼블리싱 주석 추가
            self.lblLocationInfo1.text = "보고 계신 위치" // 위치 정보 레이블 1에 텍스트 설정
            self.lblLocationInfo2.text = "이지스퍼블리싱 출판사 " // 위치 정보 레이블 2에 텍스트 설정
        }
    }
}

 

배경 색이 계속 바뀌는 앱

//
//  ViewController.swift
//  Lamp
//
//  Created by 1234 on 2024/11/06.
//

import UIKit

class ViewController: UIViewController {

    var timer: Timer? // 타이머를 저장할 변수

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // 타이머 시작: 1초마다 배경색 변경
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(changeBackgroundColor), userInfo: nil, repeats: true)
    }

    @objc func changeBackgroundColor() {
        // 랜덤한 색상 생성
        let red = CGFloat(arc4random_uniform(256)) / 255.0
        let green = CGFloat(arc4random_uniform(256)) / 255.0
        let blue = CGFloat(arc4random_uniform(256)) / 255.0

        // 배경색 변경
        view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }

    deinit {
        // 타이머가 더 이상 필요하지 않을 때 해제
        timer?.invalidate()
    }
}

 

 

출처:

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

'📱 모바일 프로그래밍 > iOS 프로그래밍 기초' 카테고리의 다른 글

iOS 프로그래밍 12주차  (0) 2024.11.20
iOS 프로그래밍 11주차  (1) 2024.11.13
iOS 프로그래밍 9주차  (0) 2024.10.30
iOS 프로그래밍 6주차  (0) 2024.10.16
iOS 프로그래밍 5주차  (0) 2024.10.13