EEYatHo 앱 깎는 이야기

Swift ) UISearchBar 네비게이션바에 넣기 본문

iOS, Swift/Tip, Bug, Swift Error

Swift ) UISearchBar 네비게이션바에 넣기

EEYatHo 2021. 3. 4. 18:30
반응형

UISearchBar 선언부

lazy var searchBar: UISearchBar = {
        let searchbar = UISearchBar()
        let placeholderText = "검색어를 입력해 주세요."
        searchbar.placeholder = placeholderText
        if let textField = searchbar.value(forKey: "searchField") as? UITextField {
            textField.backgroundColor = .white
            if let font = UIFont(name: Resource.Font.NanumSquareRoundR.rawValue, size: 16) {
                let placeholderAttributedText =  NSAttributedString(string: placeholderText,
                                                         attributes: [NSAttributedString.Key.kern: -1.0,
                                                                       NSAttributedString.Key.font: font])
                
                let attributes =  [NSAttributedString.Key.kern: -1.0,
                                   NSAttributedString.Key.font: font] as [NSAttributedString.Key: Any]
                
                textField.attributedPlaceholder = placeholderAttributedText
                textField.customFont(fontName: .NanumSquareRoundR, size: 16, letterSpacing: -1)
                textField.textColor = Resource.Color.grey05
                textField.defaultTextAttributes = attributes
                // 검색창 왼쪽 돋보기 없애기
                textField.leftViewMode = .never
            }
            
        }
        // 검색창 커서 색 설정
        UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = Resource.Color.orange06
        // 택스트 왼쪽으로 옮기기
        searchbar.setPositionAdjustment(UIOffset(horizontal: -50, vertical: 0), for: .search)
        UISearchBar.appearance().searchTextPositionAdjustment = UIOffset(horizontal: -10, vertical: 0)
        // 검색창 오른쪽 이미지 설정
        searchbar.setImage(UIImage(named: "iconCloseB24"), for: .clear, state: .normal)
        // 바로 커서 설정
        searchbar.becomeFirstResponder()
        searchbar.sizeToFit()
        // 키보드에서 검색 버튼 눌렀을 때를 수신하기 위한 델리게이트
        searchbar.delegate = self
        return searchbar
    }()

 

네비게이션 바에 넣기 ( viewDidAppear, viewWillAppear 다 됨)

override func viewDidAppear(_ animated: Bool) {
        navigationItem.titleView = searchBar
        navigationController?.view.setNeedsLayout() // force update layout
        navigationController?.view.layoutIfNeeded() // to fix height if th navigation bar
    }

네비바는 44픽셀, 검색바는 56픽셀이라 레이아웃 과정이 필요

Comments