如何在Xcode故事板中通过自定义运行时属性设置文本属性及字符间距?
Hey there, let's tackle your two questions about User Defined Runtime Attributes in Xcode Storyboards:
1. 如何使用User Defined Runtime Attributes设置defaultTextAttributes?
Setting defaultTextAttributes via User Defined Runtime Attributes is straightforward—here's a step-by-step breakdown:
- Open your Storyboard and select the target control (this works for UILabel, UITextField, UIButton's titleLabel, and other text-based components).
- Switch to the Identity Inspector (the third tab in the right-hand panel, looks like a small ID card).
- Scroll down to the User Defined Runtime Attributes section, then click the
+button to add a new attribute. - For the key path, enter
defaultTextAttributes, and set the type toDictionary. - Expand the dictionary by clicking the triangle next to it, then add sub-attributes for the text styles you want:
- To set a font: Add a child attribute with key
font, typeNSFont, and value likeSystem 17.0orHelveticaNeue-Bold 16.0. - To set text color: Add a child attribute with key
foregroundColor, typeUIColor, and pick a color from the dropdown (or enter a custom one). - You can also add other attributes like
underlineStyle(typeNSNumber, value1for single underline) orbackgroundColor(typeUIColor) to customize further.
- To set a font: Add a child attribute with key
2. 若要设置字符间距(用于拉开文本间距,示例:t h i s .),能否直接在Xcode故事板中通过User Defined Runtime Attributes实现?
Absolutely! You can add character spacing (kern) directly through User Defined Runtime Attributes by nesting it inside the defaultTextAttributes dictionary:
- Follow the steps above to create the
defaultTextAttributesdictionary for your control. - Expand the dictionary and add a new child attribute:
- Key:
kern - Type:
NSNumber - Value: Enter a numerical value (e.g.,
2for 2 points of spacing between characters; use negative numbers like-1to tighten spacing).
- Key:
- This setting will apply to all text displayed by the control—whether you set it via Storyboard or update it programmatically later (unless you explicitly override the attributed text).
A quick note for UIButton users: If you're targeting iOS versions before 15, you might need to use the key path titleLabel.defaultTextAttributes instead of just defaultTextAttributes (since UIButton's top-level defaultTextAttributes was added in iOS 15).
内容的提问来源于stack exchange,提问作者Fattie
相关产品推荐
相关产品推荐

