我想在导航栏的右上角创建一个收藏夹按钮。我想使用星形图标,所以我创建了一个UIButton并将其嵌入到UIBarButtonItem中。但是,即使我手动设置尺寸,条形按钮也是超宽的。
另一个问题是我在这里使用的图片实际上是Apple推出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
首先将UIButton
配置为自定义按钮:
let button = UIButton(type: .custom)
其次,您的图像资产很可能超大。我这样做的方法是按照Apple的指导上传重新调整的图像。然后,您还可以删除设置帧大小的代码行。
导航栏和工具栏图标大小在准备自定义导航栏和工具栏图标时,请使用以下大小作为指导,但根据需要进行调整以创建平衡。
目标尺寸72px×72px(24pt×24pt @ 3x)48px×48px(24pt×24pt @ 2x)最大尺寸84px×84px(28pt×28pt @ 3x)56px×56px(28pt×28pt @ 2x)
https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/
您可能不希望将UIBarButtonItem
与自定义视图一起使用。只需在创建条形按钮时传递实际图像:
let image = UIImage(named: "filledStar")
UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(bookmarkCourse(_:))
关于颜色,这是因为你的酒吧按钮项目的色调颜色。默认是您看到的蓝色。另外,请注意根据@ rbaldwin的评论正确扩展您的资产。