2016-09-20 108 views
4

Please Look at this image從細胞

上點擊按鈕獲取的UITableViewCell的indexPath我在UITableViewCell和那個按鈕我想要得到的UITableViewCellindexPath的點擊有一個按鈕(紅色交叉)。

現在我上的按鈕我得到的indexPath.section值這樣的點擊分配標籤給每個這樣 cell.closeButton.tag = indexPath.section 按鈕和:

@IBAction func closeImageButtonPressed(sender: AnyObject) { 
    data.removeAtIndex(sender.tag) 
    tableView.reloadData() 
} 

這是實現正確的方式或有沒有其他乾淨的方式來做到這一點?

+0

順便說一下,爲什麼在刪除節後重新加載整個表?只需調用'tableView.deleteSections(NSIndexSet(index:sender.tag),withRowAnimation:.None)'。 – ozgur

+0

雅我可以做到這一點。 –

+0

也許你可以看看下面的線程:http://stackoverflow.com/a/41629633/387507 – valvoline

回答

16

使用委託:

MyCell.swift:

import UIKit 

//1. delegate method 
protocol MyCellDelegate: AnyObject { 
    func btnCloseTapped(cell: MyCell) 
} 

class MyCell: UICollectionViewCell { 
    @IBOutlet var btnClose: UIButton! 

    //2. create delegate variable 
    weak var delegate: MyCellDelegate? 

    //3. assign this action to close button 
    @IBAction func btnCloseTapped(sender: AnyObject) { 
     //4. call delegate method 
     //check delegate is not nil with `?` 
     delegate?.btnCloseTapped(cell: self) 
    } 
} 

MyViewController.swift:

//5. Conform to delegate method 
class MyViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,MyCellDelegate { 

    //6. Implement Delegate Method 
    func btnCloseTapped(cell: MyCell) { 
     //Get the indexpath of cell where button was tapped 
     let indexPath = self.collectionView.indexPathForCell(cell) 
     print(indexPath!.row) 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell 
     //7. assign cell delegate to view controller 
     cell.delegate = self 

     return cell 
    } 
} 
0

試試這個:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    var cell = (tableView.dequeueReusableCell(withIdentifier: "MainViewCell", forIndexPath: indexPath) as! MainTableViewCell) 
    cell.myButton().addTarget(self, action: Selector("myClickEvent:event:"), forControlEvents: .touchUpInside) 
    return cell 
} 

這個功能得到行的位置單擊

@IBAction func myClickEvent(_ sender: Any, event: Any) { 
    var touches = event.allTouches()! 
    var touch = touches.first! 
    var currentTouchPosition = touch.location(inView: feedsList) 
    var indexPath = feedsList.indexPathForRow(atPoint: currentTouchPosition)! 
    print("position:\(indexPath.row)") 
} 
0

您也可以從CGPoint得到NSIndexPath這樣:

@IBAction func closeImageButtonPressed(sender: AnyObject) { 
    var buttonPosition = sender.convertPoint(CGPointZero, to: self.tableView) 
    var indexPath = self.tableView.indexPathForRow(atPoint: buttonPosition)! 
} 
+0

你能告訴我這是如何工作的嗎? –

+0

'CGPointZero'是位置(0,0)的點常量。零點相當於'CGPointMake(0,0)'。它會將你的buttonPosition轉換爲indexpath。 –

0

創建一個自定義類的UIButton的,並聲明存儲的屬性這樣的,並用它來檢索callFroRowAtIndexPath分配indexPath 。

class VUIButton: UIButton { 
    var indexPath: NSIndexPath = NSIndexPath() 
} 

這是完全證明的解決方案,您的indexPath在任何情況下都不會出錯。嘗試一次。

0

在你cellForRow:

#import <objc/runtime.h> 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    setAssociatedObject(object: YOURBUTTON, key: KEYSTRING, value: indexPath) 
} 

@IBAction func closeImageButtonPressed(sender: AnyObject) { 
    let val = getAssociatedObject(object: sender, key: KEYSTROKING) 
} 

這裏val爲您indexPath對象,您可以傳遞任何對象一樣,你可以指定傳遞池對象,並把它的按鈕操作。

-1

如何獲得細胞indexPath在斯威夫特4敲擊按鈕,按鈕選擇

@objc func buttonClicked(_sender:UIButton){ 

let buttonPosition = sender.convert(CGPoint.zero, to: self.tableView) 
let indexPath = self.tableView.indexPathForRow(at:buttonPosition) 
let cell = self.tableView.cellForRow(at: indexPath) as! UITableViewCell 
print(cell.itemLabel.text)//print or get item 
} 
0
// 
// ViewController.swift 
// Table 
// 
// Created by Ngugi Nduung'u on 24/08/2017. 
// Copyright © 2017 Ngugi Ndung'u. All rights reserved. 
// 

import UIKit 

class ViewController: UITableViewController{ 

    let identifier = "cellId" 
    var items = ["item1", "2", "3"] 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     self.title = "Table" 
     tableView.register(MyClass.self, forCellReuseIdentifier: "cellId") 
    } 

    //Return number of cells you need 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
     return items.count 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! MyClass 
     cell.controller = self 
     cell.label.text = items[indexPath.row] 
     return cell 

    } 

    // Delete a cell when delete button on cell is clicked 
    func delete(cell: UITableViewCell){ 
     print("delete") 
     if let deletePath = tableView.indexPath(for: cell){ 
      items.remove(at: deletePath.row) 
      tableView.deleteRows(at: [deletePath], with: .automatic) 
     } 

    } 

} 

class MyClass : UITableViewCell{ 
    var controller : ViewController? 
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
      super.init(style: style, reuseIdentifier: reuseIdentifier) 
      setUpViews() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     fatalError("init(coder:) has not been implemented") 
    } 

    let label : UILabel = { 
     let label = UILabel() 
     label.text = "My very first cell" 
     label.translatesAutoresizingMaskIntoConstraints = false 
     return label 
    }() 

    let btn : UIButton = { 
     let bt = UIButton(type: .system) 
     bt.translatesAutoresizingMaskIntoConstraints = false 
     bt.setTitle("Delete", for: .normal) 


     bt.setTitleColor(.red, for: .normal) 
     return bt 
    }() 

    func handleDelete(){ 
     controller?.delete(cell: self) 
    } 
    func setUpViews(){ 
     addSubview(label) 
     addSubview(btn) 
     btn.addTarget(self, action: #selector(MyClass.handleDelete), for: .touchUpInside) 
     btn.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true 
     label.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 16).isActive = true 
     label.widthAnchor.constraint(equalTo: self.widthAnchor , multiplier: 0.8).isActive = true 
     label.rightAnchor.constraint(equalTo: btn.leftAnchor).isActive = true 

    } 
} 

下面是一個完整的例子,將回答你的問題。