无法弄清楚从哪里开始子类化 UIControl!
我想创建自己的控件,其中包含几个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定需要
UIControl
吗?UIControl
类适用于相当简单、通常可重用的控件,例如需要支持有限事件集(例如“触摸”或“值更改”)的按钮和文本字段。如果您只是想创建一种将多个视图分组在一起的方法,则应该使用UIView
。无论哪种情况,您都应该执行以下操作:
创建子视图并在
-initWithFrame:
中设置其大部分属性。将它们保存在实例变量中并将它们添加为 self 的子视图。在
-layoutSubviews
中设置它们的框架,并根据self.bounds
计算它们。每当您的视图更改大小时,包括在-initWithFrame:
之后,都会调用此函数。除非您需要使用 Core Graphics 函数进行自定义绘图,否则您不需要实现
-drawRect:
。Are you sure you want
UIControl
? TheUIControl
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 useUIView
instead.In either case, here's what you should do:
Create your subviews and set most of their properties in
-initWithFrame:
. Save them in instance variables and add them as subviews of self.Set their frames in
-layoutSubviews
, calculating them based onself.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.