0

我想使用如下图所示的图像和文本设置 navigationItem 的 titleView:

在此处输入图像描述

我该如何做到这一点?

更具体地说,我正在尝试在Swift.

4

1 回答 1

5

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

在此处输入图像描述

使用我在下面编写的代码,结果是这样的:

在此处输入图像描述

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

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

}
于 2017-01-04T03:27:01.580 回答