ios - 如何知道标签是否被点击

标签 ios swift swift2

我使用 ExpandableView 创建了一个菜单,我得到了这个 github 存储库:

https://github.com/SubhiH/ExpandableTableView

实现后,我需要知道如何知道何时单击单元格的标签,因为我需要在用户单击此标签时将其重定向到另一个 View 。 每个标签都会重定向到不同的 View ,以便了解它们何时被单击。 重定向我已经知道该怎么做,但我尝试检查何时选择标签,但无法检查。

有谁知道我如何调整代码来做到这一点?

下面是菜单图片和代码示例:

Image of menu

import UIKit

class ExpandableTableViewViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!

    var selectedCellIndexPath: NSIndexPath?

    ////Heigh for cell in subTableView
    // Para pessoas que falam a língua portuguesa -> Tamanho da célula da tabela (principal e subs)
    let selectedCellHeightForSubTable: CGFloat = 40.0



    ///Heigh for cell in Main Table in (unselected)
    //Para pessoas que falam a língua portuguesa -> Tamanho da célula quando não escolhida
    let unselectedCellHeight: CGFloat = 110.0


    ////Array to save references for SubTables
    //Para pessoas que falam a língua portuguesa -> Neste array são salvas as referências para as subtabelas
    var subTables:[UITableView] = [UITableView]();


    ///fake data /// tuples type
    // Para pessoas que falam a língua portuguesa -> Aqui são instanciados os vetores que serão utilizados
    // na instanciação das células principais que serão utilizadas no armazenamento das células que irão compor
    // as tabelas e a subtabelas
    var data:([String],[[String]],[[String]],[[String]])=([String](),[[String]](),[[String]](),[[String]()]);


    override func viewDidLoad() {
        super.viewDidLoad()


        ///Register Nib file for Main Cells
        // Para pessoas que falam a língua portuguesa -> Aqui eu faço o registro dos arquivos nib que representam
        // as células principais
        tableView.registerNib(UINib(nibName: "ExpandableCellTableViewCell",bundle: nil), forCellReuseIdentifier: "cell");


        ////Initialize array with fake data
        // Para pessoas que falam a língua portuguesa -> Aqui eu tenho a presença do método InitialiDataArray()
        // que realiza a instanciação dos vetores das células principais e secundárias.
        self.data = self.InitializeDataArray()

        self.tableView.reloadData();
    }


    // Para pessoas que falam a língua portuguesa -> Retorna o número de seções na TableView
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    // Para pessoas que falam a língua portuguesa -> Ajusta as células da TableView nas subtabelas
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        ///Main table
        if tableView == self.tableView{
            return data.0.count;
        }else{
            if let index = self.subTables.indexOf(tableView) {
                return data.1[index].count+1;///+1 for Header cell in subtableView
            }
            return 0;
        }

    }


    // Para pessoas que falam a língua portuguesa -> Ajuste das células presentes nas linhas (subtabelas)
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if tableView == self.tableView {
            if selectedCellIndexPath == indexPath {

                ////unselected Heigh + heigh for every cell in subtable
                return unselectedCellHeight+selectedCellHeightForSubTable*CGFloat(self.data.1[indexPath.row].count+1)
            }
            return unselectedCellHeight
        }else{
            return selectedCellHeightForSubTable
        }
    }


    // Para pessoas que falam a língua portuguesa -> Processo de seleção das células e inclusão dos efeitos
    // de expandir e colapsar.
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if tableView == self.tableView {



            if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath {

                let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
                //let cell2 = self.tableView.cellForRowAtIndexPath(indexPath)!
                //let textoo = (cell2.viewWithTag(4) as! UILabel).text

               // print("Yuri 2")
               // print(textoo)

                cell.directionImageView.image = UIImage(named: "down");

                tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!.hidden = true;
                selectedCellIndexPath = nil


            } else {
                selectedCellIndexPath = indexPath

                let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
                cell.directionImageView.image = UIImage(named: "up");

                tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!.hidden = false;
            }




            tableView.beginUpdates()
            tableView.endUpdates()

            if selectedCellIndexPath != nil {
                // This ensures, that the cell is fully visible once expanded
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .None, animated: true)

            }
        }

    }

    // Para pessoas que falam a língua portuguesa -> Efeitos de expansão e colapso quando a célula não foi 
    //selecionada
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        if self.tableView.isEqual(tableView){
            let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
            cell.directionImageView.image = UIImage(named: "down");
            cell.viewWithTag(3)!.hidden = true;
        }

    }


    // Para pessoas que falam a língua portuguesa -> Preenchimento do conteúdo dos vetores nas células principais
    // e secundárias
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell=UITableViewCell();
        if tableView == self.tableView{
            cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
                as! ExpandableCellTableViewCell;

            (cell.viewWithTag(1) as! UILabel).text = self.data.0[indexPath.row]

            let subtable = cell.viewWithTag(3) as! UITableView;
            subtable.delegate = self;
            subtable.dataSource = self;

            subtable.registerNib(UINib(nibName: "SubTableCellTableViewCell",bundle: nil), forCellReuseIdentifier: "sub_cell");


            self.subTables.append(subtable);

            subtable.reloadData();

        }else{
            cell = tableView.dequeueReusableCellWithIdentifier("sub_cell", forIndexPath: indexPath)

            print(indexPath.row)
            print(indexPath.section)

            if indexPath.row>0{
                if let index = self.subTables.indexOf(tableView) {


                    (cell.viewWithTag(1) as! UILabel).text = self.data.1[index][indexPath.row-1]
                    (cell.viewWithTag(2) as! UILabel).text = self.data.2[index][indexPath.row-1]
                    (cell.viewWithTag(3) as! UILabel).text = self.data.3[index][indexPath.row-1]

                   // let texto = (cell.viewWithTag(1) as! UILabel).text
                   // print(texto)

                }
            }



        }

       // if("verdade".isEqualToString("verdade"))
        //{
           // print("Entrei")
        //}

        cell.selectionStyle = .None
       // let tex = (cell.viewWithTag(1) as! UILabel).text
       // print("Yuri")
       // print(tex)
        return cell;
    }



    // Para pessoas que falam a língua portuguesa -> Declaração do conteúdo das células principais e 
    // secundárias
    public func InitializeDataArray()->([String],[[String]],[[String]],[[String]]){

        var mainCells = [String]();
        var col1_SubCells = [[String]]();
        var col2_SubCells = [[String]]();
        var col3_SubCells = [[String]]();


        ////Expandable Cells Data
        mainCells.append("Genesis");
        mainCells.append("Exodus");
        mainCells.append("Leviticus");
        mainCells.append("Numbers");
        //        mainCells.append("Cell 5");

        ////First Main cell data

        ///First Col////////
        var tempArr:[String] = [String]();
        tempArr.append("Chapters")
        tempArr.append("Gen 3")
        tempArr.append("Gen 6")
        tempArr.append("Gen 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Gen 2")
        tempArr.append("Gen 5")
        tempArr.append("Gen 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Gen 1")
        tempArr.append("Gen 4")
        tempArr.append("Gen 7")


        col3_SubCells.append(tempArr);


        ////2nd Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Exo 3")
        tempArr.append("Exo 6")
        tempArr.append("Exo 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Exo 2")
        tempArr.append("Exo 5")
        tempArr.append("Exo 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Exo 1")
        tempArr.append("Exo 4")
        tempArr.append("Exo 7")


        col3_SubCells.append(tempArr);



        ////3rd Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Lev 3")
        tempArr.append("Lev 6")
        tempArr.append("Lev 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Lev 2")
        tempArr.append("Lev 5")
        tempArr.append("Lev 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Lev 1")
        tempArr.append("Lev 4")
        tempArr.append("Lev 7")


        col3_SubCells.append(tempArr);


        ////4th Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Num 3")
        tempArr.append("Num 6")
        tempArr.append("Num 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Num 2")
        tempArr.append("Num 5")
        tempArr.append("Num 8")
        tempArr.append("Num 11")

        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Num 1")
        tempArr.append("Num 4")
        tempArr.append("Num 7")
        tempArr.append("Num 10")

        col3_SubCells.append(tempArr);



        return (mainCells,col1_SubCells,col2_SubCells,col3_SubCells);
    }


}

当我单击 col3_row1 等中的示例而不是主单元格中的示例时,我想知道图像。

最佳答案

如果您搜索这样的解决方案:

let label = tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!
if (CGRectContainsPoint(label.frame, pointInCell)) {
    // user tapped image
} else {
    // user tapped cell
}

那么这个解决方案可以完美地为您量身定制:

Distinguish which part of UITableViewCell has been clicked

关于ios - 如何知道标签是否被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279282/

相关文章:

ios - NSData 初始化?(contentsOf url : URL) migration from Swift 2 to Swift 3

ios - 如何使用 Swift 在 iOS 中使用 AdMob 实现插页式广告?

ios - self?.performSegue 不显示导航栏

ios - Firebase 数据库和 Swift : Save location data in an array

ios - 无法从数组中删除元素

ios - 通过heroku解析服务器在单个设备上发送推送通知

ios - 如何快速从 UIScrollView 中的 super View 中删除 UIView 或 UIButton

swift - 索引 Metal 缓冲区的问题

ios - 是否同时调用多个 didBeginContact 调用?

ios - Swift 2.0 中的自定义 Segue : destinationViewController's navigationController property returning nil