How to put an image as the navigation bar title

前端 未结 7 1665
忘掉有多难
忘掉有多难 2020-12-04 09:04

I want to put a .png image in the middle of the navigation bar instead of the title written in text. Could you please let me know how to do that?

Thanks.

7条回答
  •  一个人的身影
    2020-12-04 09:55

    In case if someone needs both image and text inside the Navigation bar title view in Swift 4.2, please try this function:-

    override func viewDidLoad() {
    
        super.viewDidLoad()
    
        //Sets the navigation title with text and image
        self.navigationItem.titleView = navTitleWithImageAndText(titleText: "Dean Stanley", imageName: "online")
    }
    
    func navTitleWithImageAndText(titleText: String, imageName: String) -> UIView {
    
        // Creates a new UIView
        let titleView = UIView()
    
        // Creates a new text label
        let label = UILabel()
        label.text = titleText
        label.sizeToFit()
        label.center = titleView.center
        label.textAlignment = NSTextAlignment.center
    
        // Creates the image view
        let image = UIImageView()
        image.image = UIImage(named: imageName)
    
        // Maintains the image's aspect ratio:
        let imageAspect = image.image!.size.width / image.image!.size.height
    
        // Sets the image frame so that it's immediately before the text:
        let imageX = label.frame.origin.x - label.frame.size.height * imageAspect
        let imageY = label.frame.origin.y
    
        let imageWidth = label.frame.size.height * imageAspect
        let imageHeight = label.frame.size.height
    
        image.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
    
        image.contentMode = UIView.ContentMode.scaleAspectFit
    
        // Adds both the label and image view to the titleView
        titleView.addSubview(label)
        titleView.addSubview(image)
    
        // Sets the titleView frame to fit within the UINavigation Title
        titleView.sizeToFit()
    
        return titleView
    
    }
    

提交回复
热议问题