如何设置 TextField 的占位符文本以适合该字段

问题描述 投票:0回答:2

我有一个用于搜索短语的文本字段。该文本字段有一个占位符,其中包含较长的文本(日语)。在 iPhone 11 上还好,但在 SE 上就缩短了

...
。我想知道如何为本文设置自动缩放系数(例如 0.6)。

swift xcode storyboard
2个回答
0
投票

要设置 UITextField 的占位符文本以适合该字段并根据可用空间动态调整其大小,您可以使用多种策略的组合,包括动态字体大小、自定义占位符文本以及观察文本字段框架中的变化。这是分步指南:

  1. 动态字体大小:

您可以通过将字体大小设置为支持动态类型的特定样式来启用占位符文本的动态字体大小调整。动态字体大小将允许文本根据用户的辅助功能设置调整其大小。您可以在 Interface Builder 中或以编程方式执行此操作:

在界面生成器中:

选择 UITextField。 在属性检查器中,将“文本样式”属性设置为适当的动态类型样式,例如“标题”或“副标题”。 以编程方式:

textField.font = UIFont.preferredFont(forTextStyle: .headline)

2。自定义占位符文本:

如果您想更好地控制占位符文本大小和缩放系数,您可以使用属性字符串设置自定义占位符文本。您可以根据需要调整字体大小和其他属性。以下是如何以编程方式完成此操作:

let placeholderText = "Your placeholder text" // Replace with your actual placeholder text
let fontSizeFactor: CGFloat = 0.6
let attributes: [NSAttributedString.Key: Any] = [
    .font: UIFont.preferredFont(forTextStyle: .headline).withSize(UIFont.preferredFont(forTextStyle: .headline).pointSize * fontSizeFactor),
]

textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: attributes)
In this code, fontSizeFactor controls the scaling factor for the font size. Adjust it as needed.

3.框架变化观察者:

如果您想确保占位符文本根据可用空间进行调整,您可以观察 UITextField 的框架变化并相应地更新字体大小。在您的视图控制器中添加此代码:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(textFieldFrameChanged(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
}

@objc func textFieldFrameChanged(_ notification: Notification) {
    // Adjust the font size of the placeholder text based on the available space here
}

在textFieldFrameChanged方法中,您可以计算可用空间并根据您想要的缩放系数调整字体大小。

通过组合这些策略,您可以创建一个带有占位符文本的 UITextField,该文本会根据可用空间和指定的缩放因子动态调整其大小。


-1
投票

以编程方式使用占位符:

    let attributedPlaceholder = NSAttributedString(string: yourText,
                                                    attributes: [NSAttributedString.Key.foregroundColor: UIColor.darkGray])
    label.adjustsFontSizeToFitWidth = true
    label.minimumScaleFactor = 0.6
    label.attributedText = attributedPlaceholder
© www.soinside.com 2019 - 2024. All rights reserved.