我可以向 iOS 导航栏添加单色可缩放自定义图标吗?

Can I add a monochome scalable custom icon to the iOS navigation bar?

iOS' Template Icons无法涵盖所有​​必要的图标,所以我需要在导航栏中添加一个自定义图标(“···”更多图标)。

现在有没有办法给 iOS 一个单一的、可缩放的图标文件,我可以以可维护的方式着色(例如,与文本颜色相同)并且不需要为其生成位图?

OS X 使用 PDF 作为托盘图标,这样 OS X 可以根据 bright/dark 颜色主题更改图标的颜色。

你可以使用

navigationItem.rightBarButtonItem?.tintColor = UIColor.redColor()

如果您想要 tintColor 用于所有 navigationItems,您可以使用

let sharedApplication = UIApplication.sharedApplication()
sharedApplication.delegate?.window??.tintColor = UIColor.redColor()



TL;DR:

这是可能的,因为从 iOS 7 开始,UIImage 有一个 renderingMode 属性。

Create a version of this image with the specified rendering mode. By default, images have a rendering mode of UIImageRenderingModeAutomatic.

@available(iOS 7.0, *)
public func imageWithRenderingMode(renderingMode: UIImageRenderingMode) -> UIImage
@available(iOS 7.0, *)
public var renderingMode: UIImageRenderingMode { get }


关于 renderingMode

Images are created with UIImageRenderingModeAutomatic by default. An image with this mode is interpreted as a template image or an original image based on the context in which it is rendered. For example, navigation bars, tab bars, toolbars, and segmented controls automatically treat their foreground images as templates, while image views and web views treat their images as originals. You can use UIImageRenderingModeAlwaysTemplate to force your image to always be rendered as a template or UIImageRenderingModeAlwaysOriginal to force your image to always be rendered as an original.

@available(iOS 7.0, *)
public enum UIImageRenderingMode : Int {

    case Automatic // Use the default rendering mode for the context where the image is used
    case AlwaysOriginal // Always draw the original image, without treating it as a template
    case AlwaysTemplate // Always draw the image as a template image, ignoring its color information
}

我们不需要更改 navigationItem 图像的呈现模式,因为导航栏控件会自动将其前景图像视为模板。

如果需要,我们可以使用 imageWithRenderingMode() 方法更改任何 UIImage 的渲染模式以具有此功能,例如

UIImage(named: "settings")?.imageWithRenderingMode(.AlwaysTemplate)

缩放可以参考UIImage

resizableImageWithCapInsets()方法

有关详细信息,请参阅 Essan Parto
的 Ray Wenderlich 教程 UIAppearance Tutorial: Getting Started

更新:

见上图。它只有 10x10 像素。
图片可能很小,但是 iOS 知道如何使用它来绘制,因为它已经过预切片并且可以调整大小。

例子

let controlBackground = UIImage(named: "controlBackground")?
    .imageWithRenderingMode(.AlwaysTemplate)
    .resizableImageWithCapInsets(UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3))

上、左、下、右四个角保持不变,图像的中间部分将上浆。使用这个小图像,您可以制作一个大矩形,保持图像角完好无损。

您也可以将 Using xcode 切入 .xcassets