iOS navigationItem titleView图像和文本

时间:2017-01-04 00:46:22

标签: ios uinavigationcontroller navigationitem

我想设置navigationItem的titleView,其图像和文字如下图所示:

  

enter image description here

我如何实现这一目标?

更具体地说,我试图在Swift中执行此操作。

1 个答案:

答案 0 :(得分:3)

条件,你的控制器必须有navigation controller

enter image description here

使用我在下面写的代码,结果如下:

  

enter image description here

在视图控制器中,尝试下面的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    initUI()
}

// MARK: - init

func initUI() {

    let rect:CGRect = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: 64, height: 64))

    let titleView:UIView = UIView.init(frame: rect)
    /* image */
    let image:UIImage = UIImage.init(named: "01.jpg")!
    let image_view:UIImageView = UIImageView.init(image: image)
    image_view.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
    image_view.center = CGPoint.init(x: titleView.center.x, y: titleView.center.y - 10)
    image_view.layer.cornerRadius = image_view.bounds.size.width / 2.0
    image_view.layer.masksToBounds = true
    titleView.addSubview(image_view)

    /* label */
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 30, width: 64, height: 24))
    label.text = "Hello"
    label.font = UIFont.systemFont(ofSize: 12)
    label.textAlignment = .center
    titleView.addSubview(label)

    self.navigationItem.titleView = titleView

}