无法弄清楚从哪里开始子类化 UIControl!

发布于 2024-08-03 02:13:37 字数 255 浏览 2 评论 0原文

我想创建自己的控件,其中包含几个 UILabels 和几个 UITextFields。问题是我不知道从哪里开始!我是否直接子类化 UIControl,然后创建子视图并将它们添加到 init: 中的主视图中?或者我使用layoutSubviews?我需要重写drawRect:吗?

我习惯于创建“控制器”类来处理添加子视图,但如果我子类化 UIControl 那么我不确定要重写哪些方法来设置!

我以前从未这样做过,所以我真的很感激一些建议!

干杯!

I want to create my own control that will consist of several UILabels and a couple of UITextFields. The problem is I'm not sure where to start! Do I directly subclass UIControl, then create my subviews and add them to the main view in init:? Or do I use layoutSubviews? And will I need to override drawRect:?

I'm used to creating "Controller" classes that will handle adding subviews but if I subclass UIControl then I'm not sure what methods to override to set things up!

I've never done this before so I'd really appreciate a few pointers!

Cheers!

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

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

发布评论

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

评论(1

清醇 2024-08-10 02:13:37

您确定需要 UIControl 吗? UIControl 类适用于相当简单、通常可重用的控件,例如需要支持有限事件集(例如“触摸”或“值更改”)的按钮和文本字段。如果您只是想创建一种将多个视图分组在一起的方法,则应该使用 UIView

无论哪种情况,您都应该执行以下操作:

  1. 创建子视图并在 -initWithFrame: 中设置其大部分属性。将它们保存在实例变量中并将它们添加为 self 的子视图。

  2. -layoutSubviews中设置它们的框架,并根据self.bounds计算它们。每当您的视图更改大小时,包括在 -initWithFrame: 之后,都会调用此函数。

除非您需要使用 Core Graphics 函数进行自定义绘图,否则您不需要实现 -drawRect:

Are you sure you want UIControl? The UIControl class is intended for fairly simple, typically reusable controls like buttons and text fields that need to support a limited set of events (like "touched" or "value changed"). If you're just trying to create a way to group several views together, you should use UIView instead.

In either case, here's what you should do:

  1. Create your subviews and set most of their properties in -initWithFrame:. Save them in instance variables and add them as subviews of self.

  2. Set their frames in -layoutSubviews, calculating them based on self.bounds. This will be called any time your view changes size, including after -initWithFrame:.

You should not need to implement -drawRect: unless you need to do custom drawing with Core Graphics functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文