ios - 如何使用 Swift 为多个 subview 实现点击手势识别器

标签 ios swift uitableview uigesturerecognizer

我有一个带有 3 个静态单元格的 tableView,每个单元格都包含一个带有显示所需文本的标签的 subview ,我想要完成的是当用户点击 3 个 subview 中的任何一个时,以编程方式将方向从纵向旋转到横向.

我让它为第一个 subview 工作。但是,当我尝试将相同的 Tap 手势识别器添加到其他 subview 时,它仍然只适用于一个 subview 。请指教,我错过了什么?感谢您的任何输入。

纵向:

enter image description here

风景

enter image description here

TableView Controller 代码:

import UIKit

class SampleTableViewController: UITableViewController {

    @IBOutlet weak var newYorkViewWrapper: UIView!
    @IBOutlet weak var sanFranciscoViewWrapper: UIView!
    @IBOutlet weak var chicagoViewWrapper: UIView!

    //Vars
    let tapRec = UITapGestureRecognizer()


    override func viewDidLoad() {
        super.viewDidLoad()

        print("Sample view rendered.")


        //Tap gesture
        tapRec.addTarget(self, action: "tappedView")
        newYorkViewWrapper.addGestureRecognizer(tapRec)
        newYorkViewWrapper.userInteractionEnabled = true
        sanFranciscoViewWrapper.addGestureRecognizer(tapRec)
        sanFranciscoViewWrapper.userInteractionEnabled = true
        chicagoViewWrapper.addGestureRecognizer(tapRec)
        chicagoViewWrapper.userInteractionEnabled = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //--------------------------------------------------------
    // MARK: Hide status bar
    //--------------------------------------------------------
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    func tappedView(){
        let value = UIInterfaceOrientation.LandscapeLeft.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }

    //--------------------------------------------------------
    // MARK: View Orientation method
    //--------------------------------------------------------
    override func shouldAutorotate() -> Bool {
        return true
    }


}

最佳答案

when I try to add the same Tap gesture recognizer to the other subviews it still only works for one subview

您已经很好地回答了自己的问题。你不能这样做:

    newYorkViewWrapper.addGestureRecognizer(tapRec)
    sanFranciscoViewWrapper.addGestureRecognizer(tapRec)
    chicagoViewWrapper.addGestureRecognizer(tapRec)

相反,您必须创建三个不同的点击手势识别器并向每个 View 添加一个

关于ios - 如何使用 Swift 为多个 subview 实现点击手势识别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233027/

相关文章:

iOS 发布 Reference iPhoneContactList with ARC

iOS 在设置包中管理用户帐户

ios - 设置 UIContextualAction 大小

objective-c - 执行操作后显示或关闭特定的 ViewController

ios - 如何为 facebook ios sdk 设置 URLSchemes

ios - 有没有更好的方法在iOS应用中使用新的Facebook Comments插件?

iOS - 面容 ID 生物识别集成

ios - 如何在使用移动视觉人脸检测器时点击 UIView 进行捕获

swift - 尝试创建图像幻灯片

ios - 按下按钮时需要访问 UITableViewCell 的 detailTextLabel 属性