ios - 无法将图像(个人资料图片)按钮添加到 UINavigationBar
问题描述
我试图让我UINavigationBar
在左上角显示一个圆形的个人资料图片。我可以使用以下实例轻松地使其显示图像/图标。
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: icon, style: .plain, target: self, action: #selector(funcToCall))
问题在于,当尝试使用个人资料图片时,自定义视图和图像实例都不会产生所需的结果。
尝试 1 -- Swift 4(图像实例化)
let img = originalImage.withRenderingMode(.alwaysOriginal)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: img, style: .plain, target: self, action: #selector(goToProfile))
此尝试产生 以下结果。
问题:
- 即使我指定
leftBarButtonItem
了,它也出现在中间 - 我无法使用此策略生成圆形按钮,因为无法更改
cornerRadius
for。
尝试 2——Swift 4(自定义视图)
let idealButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
idealButton.setImage(imgToUse, for: .normal)
idealButton.imageView?.contentMode = .scaleAspectFill
idealButton.imageView?.layer.cornerRadius = 0.5 * idealButton.frame.width
idealButton.imageView?.layer.borderWidth = 0.75
idealButton.imageView?.layer.borderColor = rgba(240,240,240,1).cgColor
idealButton.addTarget(self, action: #selector(goToProfile), for: .touchUpInside)
navigationItem.setLeftBarButton(UIBarButtonItem(customView: idealButton), animated: false)
此尝试产生以下结果。
问题
- 图像跨越整个
UINavigationBar
. 它不受指定尺寸的限制。
任何帮助深表感谢。谢谢!
解决方案
让我们尝试UIButton
添加为子视图UINavigationBar
所以从创建按钮和设置它的属性开始(你可以lazy
在全局范围内使用变量)
lazy var idealButton: UIButton = {
let button = UIButton()
button.setImage(imgToUse, for: .normal)
button.imageView?.layer.cornerRadius = 16
... // set other button's properties (border, target, colors, etc.)
return button
}()
现在将此按钮添加为 currentnavigationController
的子视图navigationBar
guard let navigationBar = navigationController?.navigationBar else { return }
navigationBar.addSubview(idealButton)
然后只需为您的按钮设置约束(您需要根据需要设置高度和宽度,并且左侧和底部约束等于navigationBar
的约束)
idealButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
idealButton.leftAnchor.constraint(equalTo: navigationBar.leftAnchor, constant: 20),
idealButton.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -6),
idealButton.heightAnchor.constraint(equalToConstant: 32),
idealButton.widthAnchor.constraint(equalToConstant: 32)
])
推荐阅读
- angularjs - AngularJS ng-disabled not working inside
element - python - Flask: Unicode error when trying to parse POST payload
- apache-nifi - 下载并解压缩 Nifi,但当我在 WindowsServer 2017 上运行“run-nifi.bat”时收到警告
- c - C Signal not received from timer
- c - 如何在输出中使用 C 输出 ≤ 和 ≥ 符号而不是?
- runtime - Big-Theta Notation Analysis
- php - 编辑点击行的mysql数据
- html - Flexbox 100% Height Background Issue
- r - R中的三步潜在轮廓分析?
- ios - 是否可以保存 WKWebview 内容以供离线阅读?