我可以为 iOS 创建自定义文本字段和键盘而不需要子类化 UIControl 吗?

发布于 2024-12-22 13:45:58 字数 341 浏览 2 评论 0原文

我的应用程序将要求用户输入化学公式(H2O、Na^2+),并且由于下标和上标可能会使用户在输入过程中感到困惑,因此我决定制作一个自定义键盘。

当用户输入数字作为下标时,它应该在屏幕上显示为下标。我发现做到这一点的唯一方法是使用 NSAttributedString,它显然只适用于 CoreText。由于 UITextField 中无法包含 CoreText,因此我还需要创建一个自定义文本字段。我正在研究 UITextView,但文档显示字体样式必须在整个文本中保持一致,这意味着我不能有下标。

我是否需要为这两种情况创建 UIControl 的子类并从头开始?或者是否有一个替代类我可以从它开始,它已经具有键盘/文本字段的一些属性?

My app will require the user to input chemistry formulas (H2O, Na^2+), and since subscripts and superscripts may make the typing process confusing for the user, I have decided to make a custom keyboard.

When the user types in a number as a subscript, it should be displayed as a subscript on the screen. The only way I've found to do this is using NSAttributedString, which apparently only works with CoreText. Since I can't have CoreText in a UITextField, I need to create a custom text field as well. I was looking into UITextView, but the documentation reads that the font styles must be consistent throughout the text, meaning I can't have subscripts.

Do I need to subclass UIControl for both cases and start from scratch? Or is there an alternative class I can start with that already has some of the properties of keyboard/textfield?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2024-12-29 13:45:58

是的,您需要创建自己的 UIView 子类。

但是,您可以通过采用 UIKeyInput 协议、重写 canBecomeFirstResponder 使其返回 YES 并添加 UITapGestureRecognizer 来轻松支持键盘输入>:

    [self addGestureRecognizer:
     [[UITapGestureRecognizer alloc] initWithTarget:self
                                             action:@selector(becomeFirstResponder)]];

我想允许用户选择文本范围并使用自动更正,这比较困难:您需要采用协议UITextInput

自定义键盘非常简单:

  • 要么重写 inputAccessoryView,它允许您显示附加到键盘的自定义视图,
  • 要么重写 inputView,以便它返回自定义视图将显示在键盘的位置。

Yes, you need to create your own subclass of UIView.

But you can easily support keyboard input by adopting the UIKeyInput protocol, overriding canBecomeFirstResponder so it returns YES and adding a UITapGestureRecognizer:

    [self addGestureRecognizer:
     [[UITapGestureRecognizer alloc] initWithTarget:self
                                             action:@selector(becomeFirstResponder)]];

I you want to allow the user to select ranges of text and use autocorrection, that's harder: you need to adopt the protocol UITextInput.

Customizing the keyboard is really simple:

  • either, you override inputAccessoryView which allow you to display a custom view attached to the keyboard,
  • either, you override inputView so it returns a custom view that will be displayed in place of the keyboard.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文