Computer Science/swift ๋ฝ€๊ฐœ๊ธฐ - ์ฐธ๊ณ  ์‚ฌ์ดํŠธ ์ €์žฅ์†Œ

[swift] texfield์— ๊ธธ์ด์ œํ•œ๋‘๊ธฐ

_cactus 2021. 7. 31. 13:18
๋ฐ˜์‘ํ˜•

swiftUI textfield์— ๊ธธ์ด ์ œํ•œ๋‘ฌ์„œ ์ž…๋ ฅ๋ฐฉ์ง€

 

textfield์— ๊ธธ์ด๋ฅผ ์ œํ•œ๋‘ฌ์„œ ์ผ์ • ๊ธธ์ด๋ฅผ ๋„˜์–ด์„œ๋ฉด ๋”์ด์ƒ ์ž…๋ ฅ์ด ์•ˆ๋˜๊ฒŒ๋” ํ•˜๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ..!

(์™ผ์ชฝ์ด ์šฐ๋ฆฌ๊ฐ€ ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒƒ)

 

๋ฐ˜์‘ํ˜•

 

 

 

 

 

 

 

 

 

 

 

 

 

๋จผ์ €, TextLimiter ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ ๋‹ค

- Publish ๊ฐ’์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ObservableObject๋กœ ๋งŒ๋“ค์–ด์ค€๋‹ค

- ๋จผ์ € ๊ธฐ๋ณธ์ ์ธ ํ‹€์„ ์žก์•„๋ณธ๋‹ค (๋ณ€์ˆ˜๋“ค๊ณผ ๋ณ€์ˆ˜๋“ค์— ๋‹ด์„ ์˜๋ฏธ, ๋กœ์ง ๋“ฑ)

class TextLimiter: ObservableObject {
    private let limit: Int
    
    init(limit: Int) {
        self.limit = limit
    }
    
    @Published var value = ""
    @Published var hasReachedLimit = false
}

- ์—ฌ๊ธฐ์„œ limit์€ ์ œํ•œ์„ ๋‘˜ ๊ธธ์ด (character limit)

- value ๋ณ€์ˆ˜๋Š” Textfield์— ์ž…๋ ฅ๋˜๋Š” ๊ฐ’

- hasReachedLimit์€ ๊ธธ์ด์ œํ•œ์— ๋„๋‹ฌํ–ˆ๋Š”์ง€ ์•ˆํ–ˆ๋Š”์ง€๋ฅผ ํ™•์ธํ•ด์ฃผ๋Š” boolean ๊ฐ’

 

 

์œ„์—์„œ ์„ธ์šด ๋กœ์ง์„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด value๋ณ€์ˆ˜๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด updateํ•ด์ค€๋‹ค

@Published var value = "" {
    didSet {
        if value.count > self.limit {
            value = String(value.prefix(self.limit))
            self.hasReachedLimit = true
        } else {
            self.hasReachedLimit = false
        }
    }
}

๊ทธ๋Ÿผ class TextLimiter๋Š” ์•„๋ž˜์™€ ๊ฐ™์•„์งˆ ๊ฒƒ

class TextLimiter: ObservableObject {
    private let limit: Int
    
    init(limit: Int) {
        self.limit = limit
    }
    
    @Published var value = "" {
        didSet {
            if value.count > self.limit {
                value = String(value.prefix(self.limit))
                self.hasReachedLimit = true
            } else {
                self.hasReachedLimit = false
            }
        }
    }
    @Published var hasReachedLimit = false
}

์ด์ œ ์ด๋ ‡๊ฒŒ ๋งŒ๋“  ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•ด๋ณธ๋‹ค

์•„๋ž˜ ์˜ˆ์‹œ๋ฅผ ๋ณด์ž.  ํ…์ŠคํŠธ ๊ธธ์ด๋ฅผ 5๋กœ ์ œํ•œ

@ObservedObject var input = TextLimiter(limit: 5)

.border ๋ฅผ ์ด์šฉํ•ด์„œ ๊ธธ์ด์ œํ•œ์— ๋„๋‹ฌํ•˜๋ฉด ํ…์ŠคํŠธ ์ฃผ์œ„ border๋ฅผ ๋นจ๊ฐ„์ƒ‰์œผ๋กœ ์น ํ•˜๋„๋ก ํ•œ๋‹ค

TextField("ํ…์ŠคํŠธ ์ž…๋ ฅ์ฐฝ",
          text: $input.value)
    .border(Color.red,
            width: $input.hasReachedLimit.wrappedValue ? 1 : 0 )

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•