简体   繁体   English

如何在自定义 UIbutton 和 swift 处应用自定义字体?

[英]How do I apply custom font at custom UIbutton with swift?

I have added custom font in to my application and applied it custom UIButton class like below.我在我的应用程序中添加了自定义字体并将其应用自定义 UIButton class 如下所示。

import UIKit

class MainButton: UIButton {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.layer.borderColor = UIColor.lightGray.cgColor
        self.layer.borderWidth = 1
        self.layer.cornerRadius = 5
        self.tintColor = .black
        self.titleLabel?.font = UIFont(name: "Myfont", size: 14)
    }
}

But it didn't work.但它没有用。 And I tried another way like below.我尝试了另一种方式,如下所示。

import UIKit

class MainButton: UIButton {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.layer.borderColor = UIColor.lightGray.cgColor
        self.layer.borderWidth = 1
        self.layer.cornerRadius = 5
        self.tintColor = .black
        self.titleLabel?.font = UIFont(name: "Myfont", size: 14)
    }
}

and

@IBOutlet weak var MyBtn: MainButton!
MyBtn.titleLabel?.font = UIFont(name: "Myfont", size: 14)

The custom font was applied at first.首先应用了自定义字体。 But when I clicked the button, its font changed to system font.但是当我点击按钮时,它的字体变成了系统字体。 And I tried like this.我试过这样。

@IBOutlet var MyBtn: MainButton!
MyBtn.titleLabel?.font = UIFont(name: "Myfont", size: 14)

But the result was same.但结果是一样的。 So, how do I apply custom font at custom UIButton?那么,如何在自定义 UIButton 处应用自定义字体?

try this one:试试这个:

step 1: select you button第1步:select你按钮

step 2: Navigate to Identity Inspector第 2 步:导航到 Identity Inspector

step 3: assign a MainButton class to UIButton第 3 步:将MainButton class 分配给UIButton

step 4: then create IBOutlet of UIButton第 4 步:然后创建UIButtonIBOutlet

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM