ios - 如何忽略发送者参数 UIButton

标签 ios swift uibutton sender

我将函数用作 @IBAction 但现在我想将它用作普通函数。但问题是,当我尝试调用函数时,它要求我提供发件人,并期望将 UIButton 作为参数。 我怎样才能删除那个发件人,以免影响我的功能?

这是我的功能:

func addProductToCartButton(_ sender: UIButton) {
    // Start animation region
    let buttonPosition : CGPoint = sender.convert(sender.bounds.origin, to: self.productsTableView)

    let indexPath = self.productsTableView.indexPathForRow(at: buttonPosition)!

    let cell = productsTableView.cellForRow(at: indexPath) as! ProductTableViewCell

    let imageViewPosition : CGPoint = cell.productImageView.convert(cell.productImageView.bounds.origin, to: self.view)

    let imgViewTemp = UIImageView(frame: CGRect(x: imageViewPosition.x, y: imageViewPosition.y, width: cell.productImageView.frame.size.width, height: cell.productImageView.frame.size.height))

    imgViewTemp.image = cell.productImageView.image

    animationProduct(tempView: imgViewTemp)

    // End animation region
}

这里是我需要调用函数的地方:

func didTapAddToCart(_ cell: ProductTableViewCell) {
    let indexPath = self.productsTableView.indexPath(for: cell)
        addProductToCartButton( expecting UIBUTTON parameter)
    }

我试图将发件人设置为 nil 但不起作用。你有什么想法吗?

最佳答案

方法 1(推荐):

您可以将该参数设为可选:

@IBAction func addProductToCartButton(_ sender: UIButton?)
{
   // Do your stuff here
}

现在你可以这样调用它:

addProductToCartButton(nil)

方法 2(不推荐)

如果你不想让参数成为可选的,你可以这样调用它:

addProductToCartButton(UIButton()) // It's not recommended

方法 3(推荐)

再写一个实用函数,把代码加进去(把IBAction里面写的代码加到这个函数里)。不要从另一个函数调用 IBAction,而是调用这个实用函数。

关于ios - 如何忽略发送者参数 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51103258/

相关文章:

ios - 在框架中使用 Swift 中的 ObjectiveC,无需公开 ObjC 代码

ios - 如何将 UICollectionView 添加到 inputAccessoryView

ios - 使用 AutoLayout 创建顶部有图像、底部有标签的 UIButton (UIButtonTypeCustom)

ios - UIButton 自定义按钮不会在选择时更改字体颜色

ios - UIButton 边框中的生涩渐变

ios - SWRevealViewController 和传递对象

ios - 将按钮添加到 uitableviewcell 并没有出现

ios - 如何为 NSUserDefaults 指定名称

iOS 14 应用内购买请求登录/验证两次

swift - 通过关系调用核心数据属性