在视图加载时自动将焦点设置为UITableView的第一个单元格

时间:2016-08-09 06:33:24

标签: swift uitableview tvos

我一直在尝试创建一个应用程序,当视图加载时,焦点会自动转到UITableview的第一个单元格。

我尝试过使用UIFocusGuide然后在prefferedFocusView()方法中返回tableView,但这不起作用。

然后我写了这段代码

 var viewToFocus: UIView? = nil {
    didSet {
        if viewToFocus != nil {
            print("called1 ")
            self.setNeedsFocusUpdate();
            self.updateFocusIfNeeded();
        }
    }
}

override weak var preferredFocusedView: UIView? {
    if viewToFocus != nil {
        print("called2 ")

        return viewToFocus;
    } else {
        return super.preferredFocusedView;
    }
}

在视图中加载

        self.viewToFocus = myTableView

但这并没有奏效。

5 个答案:

答案 0 :(得分:7)

我可以通过在tableView.remembersLastFocusedIndexPath = true中设置viewDidLoad来获得此功能,然后我为首选焦点实施了委托方法:

func indexPathForPreferredFocusedView(in tableView: UITableView) -> IndexPath? {
   return NSIndexPath(forItem: 0, inSection: 0)
}

remembersLastFocusedIndexPath - If YES, when focusing on a table view the last focused index path is focused automatically. If the table view has never been focused, then the preferred focused index path is used.

答案 1 :(得分:1)

在tableView中:将WillDisplayCell方法添加到下面的代码

 [cell setSelected:YES animated:NO];
第一个单元格的

答案 2 :(得分:1)

您可以自动设置滚动位置以转到顶部单元格。

let topCell:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.scrollToRowAtIndexPath(topCell, atScrollPosition: UITableViewScrollPosition.None, animated: true)

我不确定这是否与preferredFocusedView的行为相同。

答案 3 :(得分:1)

将以下代码段添加到ViewController类的实现中,并调用tableview委托:

func tableView(tableView: UITableView, canFocusRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.row == 0 {
    return true
}
return false
}

答案 4 :(得分:0)

extension UITableView {

    func scrollToTop(section: Int) {
        let rows = self.numberOfRows(inSection: section)

        if rows > 0 {
            DispatchQueue.main.async {
                let indexPath = IndexPath(row: rows - 1, section: section)
                self.scrollToRow(at: indexPath, at: .top, animated: true)
            }
        }
    }
}

如果只有一个部分,则将部分替换为0

相关问题