[iOS/Swift] Navigation Bar의 Bar Button Item들의 간격 조정하기

민니·2022년 8월 18일
0

iOS

목록 보기
21/22

⬆️ 실제 당근마켓의 navigation bar

right bar button item들에 주목해 봅시닷
나는 분명 저정도의 간격을 원했는데, 그냥 navigation itembar button item을 삽입하면

이렇게 엉망진창으로 나옴 ㅠ
플젝 할 때는 일단 다른 거 할 게 많아서 미뤄뒀지만,, 끝나고 나니 얘를 꼭 해결해야 할 것 같다는 생각이 들었다


해결 방안

(정확하지 않음,, 서치+나의 생각)

  1. 라이징캠프를 하면서 계속 들었던 그냥 navigation bar 부분에 내가 custom한 UIView를 넣기
    -> 나도 이게 이상적이고 제일 쉬울 거라고 판단...
    바로 도전하려 했으나~! 내가 아직 스토리보드로 공부하는 짬이 모자란 학생이어서 그런지 autolayout without storyboard 등 공부할 게 많았고,, 라이징 테스트도 스토리보드로 한다고 했으니 조금 더 찾아보기로
  1. UIButton으로 버튼을 정의한 뒤, UIBarButtonItem의 custom view로 지정하기
    🔗 https://blog.naver.com/netrance/222182673978

-> 이거 왠지 될 것 같다!!!!!!!!


일단 해보자

  1. UIButton으로 button 정의하기
let firstButtonImage = UIImage(systemName: "bell")!
let firstButton = UIButton(frame: CGRect(x: 0, y: 0, width: firstButtonImage.size.width, height: firstButtonImage.size.height))
firstButton.tintColor = .black
firstButton.setImage(firstButtonImage, for: .normal)
        
let secondButtonImage = UIImage(systemName: "line.3.horizontal")!
let secondButton = UIButton(frame: CGRect(x: 0, y: 0, width: secondButtonImage.size.width, height: secondButtonImage.size.height))
secondButton.tintColor = .black
secondButton.setImage(secondButtonImage, for: .normal)
        
let thirdButtonImage = UIImage(systemName: "magnifyingglass")!
let thirdButton = UIButton(frame: CGRect(x: 0, y: 0, width: thirdButtonImage.size.width, height: thirdButtonImage.size.height))
thirdButton.tintColor = .black
thirdButton.setImage(thirdButtonImage, for: .normal)

✏️ 중간에 frame을 지정해야 하는 부분이 있는데, 일단 x, y 모두 0, width, height 모두 각각 image의 size로 주었다.
✏️ 다음 코드를 보면 알겠지만, rightBarButtonItems에 넣어주기 때문에, x, y가 중요한 것 같지는 않다. (실제로 그냥 아무 숫자나 넣어봤는데 딱히 변화가 없더라.)


  1. UIBarButtonItem의 custom view로 지정하고 rightBarButtonItem 배열에 넣어주기
let firstBarButton = UIBarButtonItem(customView: firstButton)
let secondBarButton = UIBarButtonItem(customView: secondButton)
let thirdBarButton = UIBarButtonItem(customView: thirdButton)
     
self.navigationItem.rightBarButtonItems = [firstBarButton, secondBarButton, thirdBarButton]

이렇게 작성해 주면,

이런 식으로 나온다!
간격이 좁아지긴 했지만, 크기가 맘에 안 들어 고민해 보다가, imageEdgeInsets을 사용해 보기로 했다.

근데 iOS15부터 없어졌단다,,, 🫢
대신 configuration을 이용하면 된다.


var configuration = UIButton.Configuration.plain()
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 0)

firstButton.configuration = configuration
secondButton.configuration = configuration
thirdButton.configuration = configuration

아까보다 더 괜찮아진 것 같다!


마무리

해결이 돼서 좋긴 하지만, 그래도 UIView로 custom하기를 꼭 해 보고 싶은데,,, 🥲
9월이 되면 storyboard 없이 앱을 만드는 것도 꼭 도전해야제,,!!!


🔗
https://blog.naver.com/netrance/222182673978

0개의 댓글