ios - 从 UITableViewCell 中快速更改标签文本颜色

标签 ios swift swift3 uigesturerecognizer

我在 TableView 中有一个 UILabel,我想在用户点击时将 UILabel 的颜色更改为红色。我正在使用 UITapGestureRecognizer 并点击 UILabel 我可以获得 UILabel 的内容,但我无法获得实际的 UILabel 因为据我所知你不能在 UIGesture 函数中有参数。

这是我的代码,它将有助于清理问题

class HomeProfilePlacesCell: NSObject {

    var Post =  [String]()

    @objc func PostTap(_ sender: UIGestureRecognizer) {
        print(Post[(sender.view?.tag)!])
    }

    func HomeProfilePlaceTVC(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, streamsModel : streamModel,HOMEPROFILE: HomeProfile, controller: UIViewController) -> UITableViewCell {

         let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTVC", for: indexPath) as! HomeTVC

         let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PostTap(_:)))
         tapGesture.delegate = self as? UIGestureRecognizerDelegate
         cell.post.addGestureRecognizer(tapGesture)

         cell.post.text = streamsModel.Posts[indexPath.row]
         cell.post.tag = indexPath.row
         Post = streamsModel.Posts

         return cell 
    }
}

我的功能是PostTap 每当用户点击 UILabel 这是 cell.post 然后我可以阅读它里面的内容 PostTap 但为了更改 UILabel 的颜色,我必须将 let cell 常量传递给 PostTap 功能。

无论如何我可以做到这一点或变通办法吗?我是 Swift 新手

最佳答案

使用 TableView 委托(delegate):[SWIFT 4.0]

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! <your Custom Cell>
    cell.<your CustomCell label name>.textColor = UIColor.red
    //OR
    cell.<your Customcell label name>.backgroundColor = UIColor.green
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}

func tableView(tableView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) 
{
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! <your Custom Cell>

    // change color back to whatever it was
    cell.<your Customcell label name>.textColor = UIColor.black
    //OR
    cell.<your Customcell label name>.backgroundColor = UIColor.white
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}

关于ios - 从 UITableViewCell 中快速更改标签文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48514166/

相关文章:

ios - 将导航栏更改为图像

ios - ReactiveCococa : Module compiled with Swift 2. 3 无法在 Swift 3.0 中导入

ios - Swift 3 DispatchGroup单次成功DispatchWorkItem

ios - 在 Swift 中集成 Adob​​e Creative SDK Image Editor

ios - 如何使用#selector 函数传递变量?以及将什么传递给 textField : UITextField?

swift - 如何通过 Swift 3 中的协议(protocol)从类公开 init() 的接口(interface)

ios - 使用 dequeueReusableCellWithIdentifier 时无法显示 detailTextLabel

ios - 苹果手机 x : keep search bar within safe zone

swift - Int 和 Uint8 swift 之间的区别

swift - Q : How to Update Boolean Value?