带有UIImage标题的导航栏

我想通过使用徽标图像(而不是纯文本)作为导航栏的标题来自定义应用程序的外观。当我使用此代码


let logo = UIImage(named: "logo.png")

self.navigationItem.titleView = logo;

我收到错误“ UIImage无法转换为UIView”。如何正确执行此操作?


慕森王
浏览 498回答 3
3回答

慕容森

放在里面 UIImageViewlet logo = UIImage(named: "logo.png")let imageView = UIImageView(image:logo)self.navigationItem.titleView = imageView

繁华开满天机

我用这个 它适用于iOS 8override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view.    let image = UIImage(named: "YOURIMAGE")    navigationItem.titleView = UIImageView(image: image)}这是一个示例,您如何使用CGRect做到这一点。override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view.    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 38, height: 38))    imageView.contentMode = .ScaleAspectFit    let image = UIImage(named: "YOURIMAGE")    imageView.image = image    navigationItem.titleView = imageView}希望这会有所帮助。

万千封印

对于Swift 4,您可以调整imageView的大小 let logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 270, height: 30)) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 270, height: 30)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "your_image") imageView.image = image logoContainer.addSubview(imageView) navigationItem.titleView = logoContainer
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS