在哪里初始化 UIButton 中的目标?特别关心IBDesignable [英] Where to initialize target in a UIButton? Particularly caring for IBDesignable
问题描述
我有一个
@IBDesignable
class Fancy:UIButton
我想
addTarget(self, action:#selector(blah),
forControlEvents: UIControlEvents.TouchUpInside)
那么应该在 UIButton 的哪个位置完成?
So where in UIButton should that be done?
1 - 我看到了 layoutSubviews
建议 - 是吗?
1 - I have seen layoutSubviews
suggested - is that right?
注意 - 实验表明 layoutSubviews
的一个问题是,当然,它可以在任何事情移动时经常调用.addTarget"将是一个坏主意.不止一次.
Note - experimentation shows that a problem with layoutSubviews
is that, of course, it can be called often, whenever things move around. It would be a bad idea to "addTarget" more than once.
2 - didMoveToSuperview
是另一个建议.
2 - didMoveToSuperview
is another suggestion.
3 - 在(其中一个)Inits 中的某个地方?
3 - Somewhere in (one of) the Inits?
注意 - 如果您在 Init 中进行实验,则会发现一个有趣的问题.在初始化期间,IBInspectable 变量尚未实际设置!(例如,我根据 IBInspectable 设置的控制样式"进行分支;它显然不能像 @IBInspectable 一样工作:在运行时不起作用!)
4 - 其他地方???
4 - Somewhere else???
我尝试在 Init 中执行此操作,并且效果很好.但它破坏了在编辑器中工作的可设计性.
I tried to do it in Init, and it worked well. But it breaks designables from working in the Editor.
经过一番折腾,我想出了这个(出于某种原因,两者都必须包括在内?)
By thrashing around, I came up with this (for some reason both must be included?)
@IBDesignable
class DotButton:UIButton
{
@IBInspectable var mainColor ... etc.
required init?(coder decoder: NSCoder)
{
super.init(coder: decoder)
addTarget(self, action:#selector(blah),
forControlEvents: UIControlEvents.TouchUpInside)
}
override init(frame:CGRect)
{
super.init(frame:frame)
}
我不知道为什么会这样,也不明白为什么会有两个不同的初始化例程.
I don't know why that works, and I don't understand why there would be two different init routines.
在 UIButton 中包含 addTarget
的正确方法是什么?
What's the correct way to include addTarget
in a UIButton?
推荐答案
如何实现 awakeFromNib
并在那里做?
How about implementing awakeFromNib
and doing it there?
当代码在 Interface Builder 的上下文中运行时,您还可以有条件地运行(或不运行)代码:
You can also conditionally run (or not run) code when it is being run in the context of Interface Builder:
#if !TARGET_INTERFACE_BUILDER
// this code will run in the app itself
#else
// this code will execute only in IB
#endif
(参见 http://nshipster.com/ibinspectable-ibdesignable/)
这篇关于在哪里初始化 UIButton 中的目标?特别关心IBDesignable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!