Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- CoreData
- TableView
- 롤케이크 자르기
- @escaping
- TableView Section
- class struct
- 프로그래머스
- ReferceCycle
- 양궁대회
- UIKit
- retain cycle
- firebase
- 강한 참조 순환
- 면접을 위한 CS전공 지식 노트
- Array vs Linked List
- Carousel CollectionView
- SWIFT
- Reference Cycle
- 자료구조
- NavigationSearchBar
- 테이블뷰 나누기
- Value Type Reference Type
- tableview section별 다른 cell적용
- til
- 면접을 위한 CS 전공 지식 노트 Tree
- coremotion
- UserDefaults
- Input Output
- CarouselCollectionview
- wil
Archives
- Today
- Total
개발하는 동글 :]
[TIL],[UIKit],[화면의 넓이에 따른 TextField 글자수 제한] 본문
1. Try
func textFieldDidChangeSelection(_ textField: UITextField) {
var text = textField.text ?? ""
let width = textField.frame.width
if width > (Constant.screenWidth - (Constant.defalutPadding * 2)) {
text.popLast()
diaryAddView.titleTextField.text = text
}
}
처음 생각해 본 접근으로는 textfield의 넓이를 주지 않은 다음 textfield의 넓이가 글자수에 따라 넓어질 때 그 넓이가 일정한 넓이보다 커질 경우 마지막 글자를 제거한 뒤 텍스트 필드에 재할당 하는 방식이다.
결과는?
위의 동영상과 같이 글자가 사라져 버렸다. 그렇기에 무슨 일이 일어나는지 확인하기 위해 프린트 코드를 추가한 후 콘솔창을 확인해 보았다.
위의 콘솔창의 결과를 보면 알 수 있듯 textField의 넓이가 줄어든 텍스트만큼 작아지지 않아 텍스트가 없어질 때까지 계속하여 반복된다 그렇다면 계속하여 if문을 타지 않도록 넓이를 변경해 주면 되지 않을까라고 생각하여 textField에 넓이를 주었다.
func textFieldDidChangeSelection(_ textField: UITextField) {
var text = textField.text ?? ""
let width = textField.frame.width
if width > (Constant.screenWidth - (Constant.defalutPadding * 2)) {
text.popLast()
print("text\(text),width\(width)")
diaryAddView.titleTextField.text = text
let frame = diaryAddView.titleTextField.frame
diaryAddView.titleTextField.frame = CGRect(x: frame.midX, y: frame.midY, width: 300, height: frame.height)
}
}
하지만 넓이는 줄어들지 않았기에 위의 콘솔과 똑같은 콘솔이 출력되었고 텍스트필드는 글자가 없어졌다. 왜 넓이를 제약할 수 없는지 알 수 없었다.
2. 혹시나 해결방법이 필요한 사람들을 위해..
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
let currentText = textField.text ?? ""
let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
let screenWidth = (Constant.screenWidth - (Constant.defalutPadding * 2))
let maxWidth = Int(screenWidth / textField.font!.pointSize)
if newText.count <= maxWidth {
return true
} else {
return false
}
}
3. 내일의 목표
1. 오늘의 문제 근본적인 해결하기
2. 제네릭, 프로토콜, 이넘 공부해서 활용하기