简体   繁体   中英

System font disappear on UIButton attributed title

I have an UIButton and I changed its title to attributed .

Now that the title is attributed I need to keep the font - "System font".

Unfortunately I can't find system font because when I made the UIButton title to attributed, I can't get this menu anymore:

好的菜单

Instead I only get this menu:

菜单不好

and here, in the larger menu, I can't find system font.

where is the system font in the menu or how can I add system font via interface builder when using UIButton attributed title?

Please don't suggest thing like "Adding a label with _______ under the UIButton" or "UIImageView with the text".

The current iOS system font is "San Francisco"

You can use it via:

UIFont.systemFont(ofSize: CGFloat, weight: UIFontWeight)

You can also download the fonts via a link on this page: https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/

There is a simpler way to do this without the storyboard.

Checkout this sample code:

class VC: UIViewController{

    @IBOutlet weak var button: UIButton! //button outlet

    override func viewDidLoad() {
        super.viewDidLoad()
        // Initialization code
        ///here we are defining the attributes for the button title...

        let textAttribute: [NSAttributedStringKey : Any] = [.foregroundColor: UIColor.blue, .font: UIFont.systemFont(ofSize: 14)]

        self.button.setAttributedTitle(NSAttributedString(string: "Button", attributes: textAttribute), for: .selected)
    }
}

From storyboard, changing attributed text back to system font can be frustrating.

Solution 1: redo it

Well, if the attributed text is simple enough, I could advise this:

  1. switch it to plain text:
    状态配置
  2. set the font back to system
  3. switch it back to attributed text
  4. re-apply the desired formatting

Solution 2: edit the XML

If the attributed string is complex, you may want to go carefully:

  1. switch to the Version Editor (or open the storyboard with an external editor like BBEdit or Sublime Text) to edit the XML source of the storyboard
    在此处输入图片说明
  2. find the guilty font, like:

     <font key="NSFont" size="17" name="ComicSansMS"/> 
  3. replace with a meta font, like:

     <font key="NSFont" metaFont="system" size="17"/> 
  4. return to the Standard Editor


Note that I rarely use attributed strings from storyboard because it can't support translations. So in general, you'll use the storyboard with some lorem ipsum , and set the adequate NSAttributedString from code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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