SWIFT TableView 没有响应

SWIFT TableView not responding

我有一个问题,我有一个控制器,在 viewdidload 中,我尝试加载从 xib 文件创建的子视图。

我的 "custom" 子视图很好地添加到我的第一个控制器,但是 table 视图没有响应...我的意思是它不滚动,当我点击它时,没有任何反应...(我还没有实现单击单元格时触发操作的方法,但是单击时单元格未突出显示)。

这里是代码:



class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let v1 = MyViewTest(frame: CGRectZero)

        v1.tableView.dataSource = self
        v1.tableView.delegate = self

        self.view.addSubview(v1)


    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //datasource method returning the what cell contains
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
        //reusing the previous scrolled cells from table view(if any)
        //cell.textLabel?.text = array[indexPath.row]
        cell.textLabel?.text = "test"
        //passing each elements of the array to cell
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //datasource method returning no. of rows
        return 14
    }


}

这里是 MyViewTest 中的代码



class MyViewTest: UIView {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!


    var view:UIView!

    let nibName:String = "MyViewTest"

    override init(frame: CGRect) {
        super.init(frame:frame)
        setup()
    }

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


    func setup() {
        view = loadViewFromNib()

        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let sWidth = screenSize.width
        let sHeight = screenSize.height
        let xPos = sWidth/2-(view.bounds.width/2)
        let yPos = sHeight/2-(view.bounds.height/2)

        view.frame = CGRectMake(xPos, yPos, view.bounds.width, view.bounds.height)

        addSubview(view)
    }

    func loadViewFromNib () -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let mview = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

        return mview
    }


}

在 xib 文件中,我只有一个带有标签的视图和我的 table视图。xib 文件与其 class(在标识符中)相关联。

如果您知道为什么我的 table 视图不起作用,那就太好了!

问题的发生是因为我用 CGRectZero 实例化了我的 MyViewTest。例如,如果我使用具有实际宽度和高度的 CGRectMake,效果会很好。

有关详细信息,请参阅上面的 rory mckinnel post:-)

您似乎将 MyTestView 的框架设置为 CGRectZero。

然后您将 table 添加为该视图的子视图,并设置了框架大小。由于 MyTestView 的宽度和高度为 0,并且视图的默认设置是不剪辑子视图,我想您可以看到 table 但不能单击它。

尝试将 MyTestView 的框架设置为屏幕大小?