Swift:将“addTarget”应用于另一个类中的UIButton

时间:2016-01-08 05:10:27

标签: ios swift uibutton

我有一个名为RecordViewFooter的班级,我在其中创建一个名为UIButton的{​​{1}}。我添加为microphoneButton,它看起来很漂亮。

但是,选择此按钮后,我需要将subview添加到subview。所以我在我的ViewController

中这样做了
ViewController

我无法弄清楚为什么在选择按钮时不会调用该功能。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

尝试修改后的代码:

def drop():

    """
    This function calculates and creates arrays for the velocity at eac time interval as well as the position and plots it. Assuming no drag. 
    """
    #Define the constants in the problem
    h_0 = 10
    g = -9.8 #gravitational constant N
    dt = 0.1 #timestep

    #Now need to create arrays to hold the positins, time, and velocities
    vel = empty(1000,float)
    time = empty(1000,float)
    y = empty(1000,float)

    time[0] = 0
    vel[0] = 0
    y[0] = h_0

    #code for the kinematic equations for the calculation of time, velocity and position
    for i in range of (1000-1):
        time[i+1] = time[i] + dt
        vel[i+1] = vel[i] + (g * dt)
        y[i+1] = time[i] + (vel[i+1] * dt)

        if y[i] > 0:
        #ensures that the graph will not keep going when the ball hits the ground
            break


    plot(time,y, '.')
    xlabel("Time(s)")
    ylabel("Position")
    show()

答案 1 :(得分:0)

您可以通过实施以下解决方案来解决该问题:

  1. 首先准备RecordViewFooter类的对象。像这里我创建了RecordViewFooter()类的对象。

    var popViewObj = UINib(nibName: "RecordViewFooter", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! RecordViewFooter
    
  2. 现在在子视图完成后编写此代码。

    popViewObj.microphoneButton.addTarget(self, action: "microphoneButtonPressed:",forControlEvents: UIControlEvents.TouchUpInside)
    
  3. 现在在代码中添加选定按钮事件:

    func microphoneButtonPressed(sender: UIButton)
    {
        print("microphone button pressed")
        // Do Whatever u want...
    }
    
  4. 它会正常工作..我希望你能完成这段代码。

答案 2 :(得分:0)

我得到了它的工作。我不得不从类中创建一个我想引用全局变量的对象。然后这样做:

    objectFromClass.globalVariable.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)