当第一个按钮来自自定义单元格而另一个按钮来自故事板时,如何制作一个对两个按钮执行相同操作的 IBAction
How to make one IBAction that does the same action to two buttons when the first one is from a custom cell and the other one is from storyboard
这来自自定义单元格:
这来自故事板:
有人知道如何让这两个按钮执行完全相同的操作吗?是否可以让多个按钮做一个动作?
我通常在我的应用程序中保持支持 UIView
s 和 UIViewController
s 非常薄,我创建 类 来完成实际的繁重工作。这使得代码更清晰,更容易重用。
class Player {
static func play() { // Static makes it easier to call from every class, assuming you only play one song at a time
// play logic goes here
}
}
class MyView: UIView {
@IBAction func play() { // connect in IB in your .xib
Player.play()
}
}
class MyViewController: UIViewController {
@IBAction func play() { // connect in IB in your storyboard
Player.play()
}
}
您需要在单独的 classes 中使用两个 IBAction 方法(用于单元格和视图控制器)。如果您想尽量减少重复代码,请尝试制作一个具有此功能的特殊 class,然后在两个 IBAction 方法中调用其方法。
为此,您还可以查看命令设计模式。
这来自自定义单元格:
这来自故事板:
有人知道如何让这两个按钮执行完全相同的操作吗?是否可以让多个按钮做一个动作?
我通常在我的应用程序中保持支持 UIView
s 和 UIViewController
s 非常薄,我创建 类 来完成实际的繁重工作。这使得代码更清晰,更容易重用。
class Player {
static func play() { // Static makes it easier to call from every class, assuming you only play one song at a time
// play logic goes here
}
}
class MyView: UIView {
@IBAction func play() { // connect in IB in your .xib
Player.play()
}
}
class MyViewController: UIViewController {
@IBAction func play() { // connect in IB in your storyboard
Player.play()
}
}
您需要在单独的 classes 中使用两个 IBAction 方法(用于单元格和视图控制器)。如果您想尽量减少重复代码,请尝试制作一个具有此功能的特殊 class,然后在两个 IBAction 方法中调用其方法。
为此,您还可以查看命令设计模式。