web-dev-qa-db-fra.com

Swift: comment rendre un UIView cliquable dans UITableViewCell?

Dans UITableViewCell, j'essaie d'implémenter un bouton avec à la fois un image et un texte.

Il semble que la norme UIButton ne puisse pas atteindre cet objectif. J'ai donc créé une UIView qui contient une UIImageView et une UILabel.

Vous pouvez voir l'implémentation ici sur le côté droit, le bouton "suivre le voyage" (le "+" est un UIImageView, et "suivre le voyage" est un UILabel)

 enter image description here

J'essaie maintenant de rendre cette UIView (c'est-à-dire le bouton) cliquable, mais je ne parviens pas à trouver un moyen.

Ceci est mon implémentation, mais ça ne marche pas:

class StationsIntroHeader: UITableViewCell {

    @IBOutlet weak var bigButton: UIView!

    override  func awakeFromNib() {
        super.awakeFromNib()
        let tap = UITapGestureRecognizer(target: self, action: Selector("followTrip:"))
        bigButton.addGestureRecognizer(tap)
    }

    func followTrip(sender:UITapGestureRecognizer) {
        print("tap working")
    }
}

Je me suis assuré que la interaction utilisateur activée est activée sur la variable UIView et désactivée sur la variable UIImageView et UILabel.

8
Daniele B

pour moi, un exemple de configuration comme celui-ci fonctionne totalement:

class TableViewController: UITableViewController {
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath)
  }
}

class CustomCell: UITableViewCell {
  @IBOutlet weak var bigButton: UIView!

  override func awakeFromNib() {
    super.awakeFromNib()
    let tap = UITapGestureRecognizer(target: self, action: Selector("bigButtonTapped:"))
    bigButton.addGestureRecognizer(tap)
  }

  func bigButtonTapped(sender: UITapGestureRecognizer) {
    print("bigButtonTapped")
  }
}

je n'ai modifié aucune des valeurs par défaut de userInteractionEnabled pour la vue ou imageview ou le libellé. compare mon implémentation avec la tienne et vois si tu as peut-être oublié quelque chose ... connecter la prise?

exemple de projet: https://www.dropbox.com/sh/hpetivhc3gfrapf/AAAf6aJ0zhvRINPFJHD-iMvya?dl=0

édite pour votre projet

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  let headerCell = tableView.dequeueReusableCellWithIdentifier("StationsIntroHeader") as! StationsIntroHeader
  headerCell.update()
  return headerCell
  // return headerCell.update().contentView
}
7
André Slotta

Vous pouvez simplement sous-classer UIButton et y implémenter le dessin personnalisé. UIButton est le moyen le plus simple de faire la tâche sans interférer avec les touches de vue de table. Si vous implémentez la manipulation du toucher dans la vue tableau, cela causera des problèmes aux contacts de cellules.

Vous pouvez simplement obtenir l'image personnalisée (le signe + et le texte en une seule image) et l'utiliser comme image d'arrière-plan. 

Ou vous pouvez même le dessiner avec du code.

Par exemple, vous pouvez essayer ceci:

 func drawCanvas1(frame frame: CGRect = CGRectMake(3, 8, 209, 109)) {
    //// General Declarations
    let context = UIGraphicsGetCurrentContext()

    //// Color Declarations
    let color = UIColor(red: 0.967, green: 0.423, blue: 0.211, alpha: 1.000)

    //// Image Declarations
    let screenShot20151111At32900PM = UIImage(named: "screenShot20151111At32900PM.png")!

    //// Rectangle Drawing
    let rectanglePath = UIBezierPath(roundedRect: CGRectMake(frame.minX + 39, frame.minY + 23, 113, 46), cornerRadius: 8)
    color.setFill()
    rectanglePath.fill()


    //// Rectangle 2 Drawing
    let rectangle2Rect = CGRectMake(frame.minX + 51, frame.minY + 27, 33, 34)
    let rectangle2Path = UIBezierPath(rect: rectangle2Rect)
    CGContextSaveGState(context)
    rectangle2Path.addClip()
    screenShot20151111At32900PM.drawInRect(CGRectMake(floor(rectangle2Rect.minX - 16 + 0.5), floor(rectangle2Rect.minY - 15 + 0.5), screenShot20151111At32900PM.size.width, screenShot20151111At32900PM.size.height))
    CGContextRestoreGState(context)


    //// Text Drawing
    let textRect = CGRectMake(frame.minX + 97, frame.minY + 23, 73, 46)
    let textTextContent = NSString(string: "\nfollow\ntrip\n")
    let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
    textStyle.alignment = .Left

    let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.labelFontSize()), NSForegroundColorAttributeName: UIColor.whiteColor(), NSParagraphStyleAttributeName: textStyle]

    let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
    CGContextSaveGState(context)
    CGContextClipToRect(context, textRect);
    textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
    CGContextRestoreGState(context)
}

et le résultat sera quelque chose comme:

 enter image description here

0
Teja Nandamuri