在UIButton中初始化目标的位置?特别关心IBDesignable

Fat*_*tie 5 initializer uibutton ios swift

我有一个

@IBDesignable
class Fancy:UIButton
Run Code Online (Sandbox Code Playgroud)

我想要

addTarget(self, action:#selector(blah),
   forControlEvents: UIControlEvents.TouchUpInside)
Run Code Online (Sandbox Code Playgroud)

那么UIButton应该在哪里完成?

最好的地方在哪里addTarget

1 - 我见过layoutSubviews建议 - 是吗?

注意 - 实验表明,问题layoutSubviews在于,当事物四处移动时,它可以经常被调用."addTarget"不止一次是一个坏主意.

2 - didMoveToSuperview是另一个建议.

3 - Inits中的某个(某个)?

注意 - 如果你在Init中进行实验,那么实验会显示一个引人入胜的问题.在Init期间,IBInspectable变量尚未实际设置!(例如,我根据IBInspectable设置的控件的"样式"进行分支;它不能用作@IBInspectable:在运行时不起作用!)

4 - 其他地方???

我尝试在Init中做到这一点,并且效果很好.但它打破了编辑工作中的可设计性.

在此输入图像描述

通过捶打,我想出了这个(出于某种原因,两者都必须包括在内?)

@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)
        }
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会这样,我不明白为什么会有两个不同的init例程.

包含addTarget在UIButton中的正确方法是什么?

Tom*_*ift 2

awakeFromNib在那里实施和做怎么样?

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSNIbAwaking_Protocol/#//apple_ref/occ/instm/NSObject/awakeFromNib

当代码在 Interface Builder 的上下文中运行时,您还可以有条件地运行(或不运行)代码:

#if !TARGET_INTERFACE_BUILDER
    // this code will run in the app itself
#else
    // this code will execute only in IB
#endif
Run Code Online (Sandbox Code Playgroud)

(参见http://nshipster.com/ibinspectable-ibdesignable/