UIBarButtonItem 的形状不正确

UIBarButtonItem not in correct shape

我想在导航栏的右上角创建一个收藏夹按钮。我想使用星形图标,所以我创建了一个 UIButton 并将其嵌入到 UIBarButtonItem 中。但是,即使我手动为它设置大小,栏按钮也超宽。

还有一个问题就是我这里用的图其实是苹果iOS编程教程入门的白星。但是,它出现在屏幕上是一颗蓝色的星星。我不知道为什么。

let button = UIButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
button.setImage(UIImage(named: "filledStar"), for: .normal)
button.addTarget(self, action: #selector(bookmarkCourse(_:)), for: .touchUpInside)

let barButtonItem = UIBarButtonItem(customView: button)
navigationItem.rightBarButtonItem = barButtonItem

您可能不想将 UIBarButtonItem 与自定义视图一起使用。创建栏按钮时只需传递实际图像即可:

let image = UIImage(named: "filledStar")
UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(bookmarkCourse(_:))

关于颜色,那是因为您的条形按钮项目的色调。默认值是您看到的蓝色。另外,请注意根据@rbaldwin 的评论正确扩展您的资产。

首先将您的 UIButton 配置为自定义按钮:

let button = UIButton(type: .custom)

其次,您的图片资源很可能尺寸过大。我这样做的方法是根据 Apple 的指导上传重新缩放的图像。然后,您还可以删除设置帧大小的代码行。

Navigation Bar and Toolbar Icon Size Use the following sizes for guidance when preparing custom navigation bar and toolbar icons, but adjust as needed to create balance.

Target sizes 72px × 72px (24pt × 24pt @3x) 48px × 48px (24pt × 24pt @2x) Maximum sizes 84px × 84px (28pt × 28pt @3x)56px × 56px (28pt × 28pt @2x)

https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/