You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TabBarController切换后导航栏圆形UIBarButtonItem图片拉伸问题

解决TabBar切换后导航栏圆形按钮拉伸变形问题

问题根源在于这几点:

  • viewDidLoad仅在初始化时设置按钮frame和cornerRadius,TabBar切换导致页面布局重调时,按钮实际bounds变化但cornerRadius未同步更新
  • 仅靠frame设置按钮尺寸,未添加约束固定大小,UIBarButtonItem的customView可能被系统布局修改尺寸
  • imageView?.contentMode = .scaleToFill会导致图片强制拉伸变形

修正方案

  1. 给按钮添加明确的宽高约束,固定按钮尺寸
  2. 在viewDidLayoutSubviews中设置cornerRadius(此处能获取按钮最终的bounds)
  3. 调整图片contentMode为.scaleAspectFill,避免图片拉伸

修改后的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    
    infoButton = UIButton(type: .custom)
    // 移除frame设置,改用约束固定尺寸
    infoButton.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        infoButton.widthAnchor.constraint(equalToConstant: 40),
        infoButton.heightAnchor.constraint(equalToConstant: 40)
    ])
    
    infoButton.sd_setBackgroundImage(with: URL(string: "https://www.w3schools.com/howto/img_avatar.png"), for: .normal)
    infoButton.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside)
    infoButton.clipsToBounds = true
    infoButton.layer.borderWidth = 1.0
    infoButton.imageView?.contentMode = .scaleAspectFill // 修改contentMode
    infoButton.layer.borderColor = UIColor.init(hexString: "#AAC8FF").cgColor
    
    let infoItem = UIBarButtonItem(customView: infoButton)
    self.navigationItem.leftBarButtonItem = infoItem
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // 每次布局完成后更新cornerRadius,确保基于当前bounds计算
    infoButton.layer.cornerRadius = infoButton.bounds.size.width / 2
}

补充说明

  • translatesAutoresizingMaskIntoConstraints = false是为了让自定义控件遵循我们添加的约束,而非系统自动生成的约束
  • viewDidLayoutSubviews会在每次视图布局变化时触发(包括TabBar切换回来后的布局调整),此时设置cornerRadius能保证按钮始终保持圆形

内容的提问来源于stack exchange,提问作者kiran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:10:36