Can I set image as a title to UINavigationBar?

后端 未结 16 1851
有刺的猬
有刺的猬 2020-12-07 09:38

Is it possible to set some image as title of Navigation bar?

I think NYTimes application used a Navigation bar and title is look like image file (the reason why it\'

16条回答
  •  轮回少年
    2020-12-07 10:30

    Do it quickly using storyboard and @IBDesignable:

    @IBDesignable class AttributedNavigationBar: UINavigationBar {
    
        @IBInspectable var imageTitle: UIImage? = nil {
    
            didSet {
    
                guard let imageTitle = imageTitle else {
    
                    topItem?.titleView = nil
    
                    return
                }
    
                let imageView = UIImageView(image: imageTitle)
                imageView.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
                imageView.contentMode = .scaleAspectFit
    
                topItem?.titleView = imageView
            }
        }
    }
    

    Then in attributes inspector just select an image:

    and wait a second for result:

    So setting view is there where it should be... in storyboard.

提交回复
热议问题