addTarget到集合视图的nib内的按钮操作

时间:2018-02-05 11:06:34

标签: ios swift uicollectionview custom-keyboard openurl

我在iOS 11中有一个键盘扩展,其中包含来自JSON的文章的集合视图。我在原型单元格中有一个按钮,我想让用户按下以在键盘外部的Safari中打开文章。我可以让它打开静态URL中的所有链接,但我无法打开每个文章的URL。我错过了什么?

我已经举了一个简单的静态动作的例子,还包括我尝试但在这段代码中不起作用的内容:

img

1 个答案:

答案 0 :(得分:2)

您无法添加任何其他DataTypes作为参数。因为,您要为UIButton添加addTarget。

@objc func openLink(){

}

@objc func openLink(sender: UIButton){ // URL is not possible.

}

以上两个代码是相同的。在第二个中,您可以访问UIButton's property

可运行代码

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if(collectionView == self.key.colImages)
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gifCollectionViewCell", for: indexPath) as! gifCollectionViewCell
        cell.lblTitle.text = self.articles[indexPath.row].headline
        let prefix: String = "https://res.cloudinary.com/djvbbwrnm/image/fetch/"
        let options: String = "w_0.2/"
        if let imageURL =  self.articles[indexPath.row].imageURL
        {

            //let articleURL = self.articles[indexPath.row].url
            //let url = URL(string: articleURL!)
            let urlAppended = prefix+options+imageURL
            cell.imgView.sd_setImage(with: URL(string: urlAppended), completed: nil)

            //This works 
            cell.shareButton.addTarget(self, action: #selector(openLink), for: .touchUpInside)

            //This doesn't
            //cell.shareButton.addTarget(self, action: #selector(openUrl(url: url)), for: .touchUpInside)

            cell.shareButton.tag = indexPath.row // SET TAG TO UIBUTTON

        }

        return cell
    }
    else
    {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "catCollectionViewCell", for: indexPath) as! catCollectionViewCell
        cell.imgView.image = buttPics[indexPath.row]
        cell.imgView.layer.cornerRadius = 2
        cell.imgView.layer.masksToBounds = true
    return cell
    }

}


@objc func openLink(sender: UIButton){ // USE THIS.

     let buttonTag : Int = sender.tag
     let articleURL = self.articles[buttonTag].url
     let url = URL(string: articleURL!)
     // You can achieve by this way.

    // Since I am in a keyboard extension, I added the follwoing code and it is working now.
   let selector = sel_registerName("openURL:")
    var responder = self as UIResponder?
    while let r = responder, !r.responds(to: selector) {
        responder = r.next
    }
    _ = responder?.perform(selector, with: url)
}