[Udemy] Section 10

서희찬·2022년 5월 31일
0

swift

목록 보기
13/17
post-thumbnail

Update the storyLabel and Button Titles

버튼의 타이틀을 바꾸기 위해서는
btn.title로는 안된다.
stackoverflow에 검색결과

button.setTitle("Button Title", for: .normal)

이런방식으로 작성해야지
버튼의 타이틀을 바꿀 수 있음을 알 수 있다.

그 결과 성공적으로 바뀐것이 확인 가능하다.

Create a Structure

Stroy.swift에 구조체를 만들어주자.

import Foundation

struct Story {
    let title : String
    let choice1 : String
    let choice2 : String
    
    init(t: String, c1: String, c2: String) {
        title = t
        choice1 = c1
        choice2 = c2
    }
    
}

이런식으로 만들면
viewcontroller.swift에서 아래와 같이 불러올 수 있다.

3가지 스토리를 담고 있는 배열을 만들어보자.

    let quiz = [
       Story(t: "You ~~", c1: "take Left", c2: "right"),
       Story(t: "You see a tiger", c1: "shout", c2: "play dead"),
       Story(t: "You find a treasure chest", c1: "Open", c2: "trap"),
    ]

이런식으로 작성해주었다.

Update the Story


버튼 선택별로 다른 값이 나오게 해주자.

    @IBAction func choiceMade(_ sender: UIButton) {
        let userAnswer = sender.currentTitle!
        
        //만약 유저대답 => choice1 ->보물
        //만약 유저대답 => choice2 ->호랑이
        
        if userAnswer == "take Left"{
            storyLabel.text = quiz[2].title
            choice1Button.setTitle(quiz[2].choice1, for: .normal)
            choice2Button.setTitle(quiz[2].choice2, for: .normal)
        }else{
            storyLabel.text = quiz[1].title
            choice1Button.setTitle(quiz[1].choice1, for: .normal)
            choice2Button.setTitle(quiz[1].choice2, for: .normal)
        }

IBAction으로 조건문을 줘서 원하는대로 해줄 수 있다.

MVC

Model
View
Controll 나눠보쟈아

import Foundation

struct Story {
    let title: String
    let choice1: String
    let choice1Destination: Int
    let choice2: String
    let choice2Destination: Int
}

스토리는 이런 방식으로 해준다.
그리고 1번선택지와 이어줄 인덱스를 저장해주는 choice1Destination을 받아준다.

이제 StroyBrain을 작성해주자

import Foundation

struct StoryBrain {
    
    var storyNumber = 0
    
    let stories = [
        Story(
            title: "공부하는데 배고프다",
            choice1: "밥 먹으러가자", choice1Destination: 2,
            choice2: "굶자", choice2Destination: 1
        ),
        Story(
            title: "굶으니깐 집중안된다",
            choice1: "밥 먹으러가자", choice1Destination: 2,
            choice2: "참고 공부하자", choice2Destination: 3
        ),
        Story(
            title: "배 부르니깐 잠온다..",
            choice1: "조금만 잘까..?", choice1Destination: 4,
            choice2: "더 잠오기전에 공부하러가자", choice2Destination: 3
        ),
        Story(
            title: "공부하니깐 잠온다...잘까?",
            choice1: "조금만 자고 다시 오자", choice1Destination: 5,
            choice2: "잠은 무슨 잠 공부나 하자", choice2Destination: 5
        ),
        Story(
            title: "공부를 안해서 행복합니다~!~",
            choice1: "The", choice1Destination: 0,
            choice2: "End", choice2Destination: 0
        ),
        Story(
            title: "공부하다 죽었습니다..",
            choice1: "The", choice1Destination: 0,
            choice2: "End", choice2Destination: 0
        )
    ]
    
    func getStoryTitle() -> String {
        return stories[storyNumber].title
    }
    
    func getChoice1() -> String {
        return stories[storyNumber].choice1
    }
    
    func getChoice2() -> String {
        return stories[storyNumber].choice2
    }
    
    mutating func nextStory(userChoice: String) {
        //유저
        
        let currentStory = stories[storyNumber] // 0부터시작
        if userChoice == currentStory.choice1 { //1번 선택
            storyNumber = currentStory.choice1Destination // 1번 선택 길로
        } else if userChoice == currentStory.choice2 { //2번 선택
            storyNumber = currentStory.choice2Destination // 2번 선택 길로
        }
    }
    
}

이렇다.

하나씩 뜯어봐보자

    func getStoryTitle() -> String {
        return stories[storyNumber].title
    }
        func getChoice1() -> String {
        return stories[storyNumber].choice1
    }
    
    func getChoice2() -> String {
        return stories[storyNumber].choice2
    }

스토리 제목과 선택지를 반환해주는 메서드들이다.

mutating func nextStory(userChoice: String) {
        //유저
        
        let currentStory = stories[storyNumber] // 0부터시작
        if userChoice == currentStory.choice1 { //1번 선택
            storyNumber = currentStory.choice1Destination // 1번 선택 길로
        } else if userChoice == currentStory.choice2 { //2번 선택
            storyNumber = currentStory.choice2Destination // 2번 선택 길로
        }
    }

그리고 스토리를 하나하나 다음으로 이어갈 수 있게 만든 메서드이다.

이제 C를 보자

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var storyLabel: UILabel!
    @IBOutlet weak var choice1Button: UIButton!
    @IBOutlet weak var choice2Button: UIButton!
    
    var storyBrain = StoryBrain() //Model struct 가져오기
    
    override func viewDidLoad() {
        super.viewDidLoad()
        updateUI()

    }

    @IBAction func choiceMade(_ sender: UIButton) {
        
        storyBrain.nextStory(userChoice: sender.currentTitle!) // 유저선택
        
        updateUI()
     
    }
    
    func updateUI() {
        storyLabel.text = storyBrain.getStoryTitle()
        choice1Button.setTitle(storyBrain.getChoice1(), for: .normal)
        choice2Button.setTitle(storyBrain.getChoice2(), for: .normal)
    }
    
}

보면 유저의 선택지를 바로 nextstory에게 전달해준다.
이렇게 되면 next스토리는 유저가 선택한값을 인식하고
그것이 초이스1인지 2인지 확인한다.
그리고 초이스1이라면 초이스1에 저장된 루트로
2라면 2에 저장된 루트로 이동한다
그러고 updateUI를 진행하는데
이는 UI를 업데이트 하면서 버튼을 쏴악 다시 적어주는 과정을 보여준다.

profile
부족한 실력을 엉덩이 힘으로 채워나가는 개발자 서희찬입니다 :)

0개의 댓글