📱 iOS/-- UIKit

(iOS) UITabBar, UINavigationBar shadow 제거, border 제거

Newmon 2023. 4. 25. 14:07

2023. 4. 25.

 

 

 

문제

Custom TabBar와 NavigationBar 를 만들일이 생겼는데 VC와 닿는부분에 자꾸 Border? Shadow? 같은 줄이 하나 생긴다.
Hierarchy를 보니 최상위 계층에 까만 ImageView가 뜬다.

 

그래서 구글링을 좀 해보니 UINavigationBarAppearance 객체의 backgroundImage 프로퍼티와 shadowImage프로퍼티에 빈 이미지를 넣어주면 원하는대로 색을 변경할 수 있다는 글을 보았다.

if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.backgroundImage = UIImage()
            appearance.shadowImage = UIImage()
}

요렇게 넣어줘봤는데 왜인지 그대로 까만 ImageView가 떴다.

해결

아마 UIImage()를 넣어도 색상변화는 없기 떄문이 아닐까 싶어서 UIGraphicsGetImageFromCurrentImageContext를 사용해서 직접 단색이미지를 만들기로 했다.

이미지 생성

func colorForNavBar(_ color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)

        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image ?? UIImage()
    }

appearance setting

if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.backgroundImage = colorForNavBar(color: .white)
            appearance.shadowImage = colorForNavBar(color: .white)
}

TabBar의 경우에도 UINavigationBarAppearance 가 아닌, UITabBarAppearance를 사용하면 똑같이 적용된다.