如何使用Swift在ios中设置按钮上的图标?

时间:2016-03-30 07:00:26

标签: ios swift uibutton

我想使用Swift中的IOS按钮上的图标,就像Android中按钮上的图标一样。有没有办法没有设置图像或没有fontAwesome图标来设置按钮上的图标?

7 个答案:

答案 0 :(得分:21)

通过Swift 3和Swift 4中的代码:

yourButton.setImage(UIImage(named: "imgName"), for: .normal)

或背景图片:

yourButton.setBackgroundImage(UIImage(named: "imgName"), for: .normal)

通过故事板:

您还可以通过情节提要设置按钮的图标,在按钮元素的image中设置attributes inspector。如果您想在图片上添加标题,请在属性检查器的background中设置图片

enter image description here

答案 1 :(得分:11)

enter image description here

    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

  

视图的插入距离。边缘插入值应用于矩形以缩小或扩展该矩形表示的区域。通常,在视图布局期间使用边缘插入来修改视图的框架。正值会导致帧以指定的量插入(或缩小)。负值会导致框架以指定的数量开始(或扩展)。

答案 2 :(得分:3)

使用此代码将图像(图标)设置为按钮。

myButton.setImage(UIImage(named: "nameOfImage.png"), forState: UIControlState.Normal)

答案 3 :(得分:3)

对于FontAwesome,您可以在github上使用插件。

https://github.com/thii/FontAwesome.swift

然后你可以很容易地设置图标:

button.titleLabel?.font = UIFont.fontAwesomeOfSize(30)
button.setTitle(String.fontAwesomeIconWithName(.Github), forState: .Normal)

并且不需要关心不同设备(x1,x2,x3)的图像分辨率,因为字体是矢量。

答案 4 :(得分:1)

以下解决方案适用于居中按钮,因为图标将始终显示在标题标签旁边。

我为此构建了一个简单的扩展名(我使用了IonIcons-字体,但是显然您可以使用任何一种字体,例如Font-Awesome):

someFunc

因此,您可以像这样在整个项目中轻松调用它:

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
    }
}

答案 5 :(得分:0)

如果您不想使用第三方插件,则可以执行

if let font = UIFont(name: "FontAwesomeFontName", size: 18) {
    button.titleLabel?.font = font
    button.setTitle("\u{f053}", for: .normal)
}

并使用fontawesome cheatsheet作为您想要的特定图标的参考。

答案 6 :(得分:0)

在Swift-5中...

btnNavBar.titleLabel?.font = UIFont(name: "Font Awesome 5 Free", size: 20)
btnNavBar.setTitle("\u{f007}", for: .normal)