在Swift中将图像添加到View Controller的居中标题右侧

时间:2018-12-30 16:55:57

标签: ios uiviewcontroller uiimage uinavigationbar

在SO上有很多答案,涉及如何使用titleView沿着图像替换视图控制器的标题:

let myimage: UIImage = UIImage(named: "myimage.png")!
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
imageView.image = image
self.navigationItem.titleView = imageView 

此外,您还可以将标题和图像都放在视图and center it中。

extension UIViewController {func setTitle(_ title: String, andImage image: UIImage) {
            let titleLbl = UILabel()
            titleLbl.text = title
            titleLbl.textColor = UIColor.white
            titleLbl.font = UIFont.systemFont(ofSize: 20.0, weight: .bold)
            let imageView = UIImageView(image: image)
            let titleView = UIStackView(arrangedSubviews: [imageView, titleLbl])
            titleView.axis = .horizontal
            titleView.spacing = 10.0
            navigationItem.titleView = titleView
        }
    }

call with: `setTitle("yourTitle", andImage: UIImage(named: "yourImage"))`

但是,我想要的是以常规方式将标题居中(宽度可能会变化),然后将图像向右固定距离。

有没有简单的方法可以做到这一点?

0 个答案:

没有答案