【发布时间】:2016-07-18 00:59:02
【问题描述】:
我想在 Swift 中使用 IOS 中按钮上的图标,就像 Android 中按钮上的图标一样。有没有什么办法不设置图片或者不设置fontAwesome图标在按钮上设置图标?
【问题讨论】:
我想在 Swift 中使用 IOS 中按钮上的图标,就像 Android 中按钮上的图标一样。有没有什么办法不设置图片或者不设置fontAwesome图标在按钮上设置图标?
【问题讨论】:
通过 Swift 3 和 Swift 4 中的代码:
yourButton.setImage(UIImage(named: "imgName"), for: .normal)
或用于背景图片:
yourButton.setBackgroundImage(UIImage(named: "imgName"), for: .normal)
通过故事板:
您还可以通过情节提要设置按钮的图标,在按钮元素的attributes inspector 中设置image。如果你想在你的图片上加上一个标题,请在属性检查器的background 中设置你的图片
来自cmets的问题
如何将图像放在“按钮”文本旁边?
您可以通过代码来做到这一点,例如设置按钮的imageEdgeInsets。下面的示例将图像放置在文本的右侧
yourButton.setImage(UIImage(named: “imgNameWhichYouWantToSetAlongsideTheButton"), for: .normal)
yourButton.imageEdgeInsets = UIEdgeInsets(top: 3, left: 0, bottom: 0, right: -8)
【讨论】:
let icon = UIImage(named: "bmiCalculator")!
button.setImage(icon, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
UIEdgeInsets
视图的插入距离。边缘插入值应用于矩形以缩小或扩展该矩形表示的区域。通常,在视图布局期间使用边缘插入来修改视图的框架。正值会导致帧被插入(或缩小)指定的量。负值会导致框架以指定的量开始(或扩展)。
【讨论】:
使用此代码为您的按钮设置图像(图标)。
myButton.setImage(UIImage(named: "nameOfImage.png"), forState: UIControlState.Normal)
【讨论】:
对于 FontAwesome,您可以使用 github 上的插件。
https://github.com/thii/FontAwesome.swift
然后你就可以很容易地设置图标了:
button.titleLabel?.font = UIFont.fontAwesomeOfSize(30)
button.setTitle(String.fontAwesomeIconWithName(.Github), forState: .Normal)
并且不需要关心不同设备(x1、x2、x3)的图像分辨率,因为字体是矢量。
【讨论】:
以下解决方案适用于居中按钮,因为图标将始终显示在标题标签旁边。
我为它构建了一个简单的扩展(我使用了IonIcons-Font,但显然你可以使用任何类型的字体,例如Font-Awesome):
extension UIButton {
func addIcon(icon: String, font:String = IonIcons.fontName.rawValue, fontSize: CGFloat = 16, text: String, color:UIColor) {
let iconWithPlaceholder = icon + " "
let iconRange = (iconWithPlaceholder as NSString).range(of: icon)
let attributedString = NSMutableAttributedString(string: iconWithPlaceholder + text)
attributedString.addAttributes([NSAttributedString.Key.font: UIFont(name: IonIcons.fontName.rawValue, size: fontSize) as Any], range: iconRange)
self.setAttributedTitle(attributedString, for: .normal)
self.tintColor = color
}
}
因此您可以像这样从整个项目中轻松调用它:
self.myButton.addIcon(icon: IonIcons.navigateOutline.rawValue, text: "Start", color: .white)
【讨论】:
如果你不想使用第三方插件,你可以这样做
if let font = UIFont(name: "FontAwesomeFontName", size: 18) {
button.titleLabel?.font = font
button.setTitle("\u{f053}", for: .normal)
}
并使用fontawesome cheatsheet 作为您想要的特定图标的参考。
【讨论】:
在 Swift-5 中...
btnNavBar.titleLabel?.font = UIFont(name: "Font Awesome 5 Free", size: 20)
btnNavBar.setTitle("\u{f007}", for: .normal)
【讨论】: