我想使用图像和文本(如下图)设置navigationItem的titleView:
我该如何实现?
更具体地说,我正在尝试在Swift
中执行此操作。
最佳答案
条件,您的控制器必须具有其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
}