ios 在 UITableView 中选择第一行作为默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2728152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:10:31  来源:igfitidea点击:

Select First Row as default in UITableView

iosuitableviewuikit

提问by tushar maniyar

I have an application that is viewbased and I am adding a tableview as a subview to the main view. I have taken UITableViewDelegateto respond the table methods. Everything is working fine, but I want to select the first row or UITableViewas default selected(Highlighted).

我有一个基于视图的应用程序,我正在添加一个 tableview 作为主视图的子视图。我采取UITableViewDelegate了响应表的方法。一切正常,但我想选择第一行或UITableView默认选择(突出显示)。

Please help me, with what code I need and where I need to put it.

请帮助我,我需要什么代码以及我需要把它放在哪里。

回答by Zain Raza

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
}

The best way to use this in your code, if you want to select any row by default, use in viewDidAppear.

如果你想选择在默认情况下,在viewDidAppear使用任何行的最佳方式在你的代码中使用此。

回答by Sourabh Sharma

Swit 3.0 updated Solution

Swit 3.0 更新解决方案

let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)

回答by Ankit Vyas

- (void)viewWillAppear:(BOOL)animated
    {

       [super viewWillAppear:animated];

     // assuming you had the table view wired to IBOutlet myTableView

        // and that you wanted to select the first item in the first section

        [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
    }

回答by malhal

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];

    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    }
}

回答by natec

Here's how to do this in Swift 1.2:

以下是在 Swift 1.2 中执行此操作的方法:

override func viewWillAppear(animated: Bool) {
    let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.selectRowAtIndexPath(firstIndexPath, animated: true, scrollPosition: .Top)
}

回答by Sanket Ray

Swift 4 Update:

斯威夫特 4 更新:

func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let indexPath = IndexPath(row: 0, section: 0)
    myTableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
}

Change row and section values if you want to select any other row in a different section.

如果您想选择不同部分中的任何其他行,请更改行和部分值。

回答by Alejandro Iván

To only select the first cell the first time the table is loaded, one would think that using viewDidLoadis the right place to go, but, at that time of execution, the table hasn't loaded its contents, so it will not work (and probably crash the app since the NSIndexPathwill point to a non-existent cell).

在第一次加载表格时只选择第一个单元格,人们会认为 usingviewDidLoad是正确的地方,但是,在执行的时候,表格还没有加载它的内容,所以它不会工作(和可能会导致应用程序崩溃,因为NSIndexPathwill 指向一个不存在的单元格)。

A workaround is to use a variable that indicates that the table has loaded before and do the work accordingly.

一种解决方法是使用一个变量来指示该表之前已加载并相应地进行工作。

@implementation MyClass {
    BOOL _tableHasBeenShownAtLeastOnce;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _tableHasBeenShownAtLeastOnce = NO; // Only on first run
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ( ! _tableHasBeenShownAtLeastOnce )
    {
        _tableHasBeenShownAtLeastOnce = YES;
        BOOL animationEnabledForInitialFirstRowSelect = YES; // Whether to animate the selection of the first row or not... in viewDidAppear:, it should be YES (to "smooth" it). If you use this same technique in viewWillAppear: then "YES" has no point, since the view hasn't appeared yet.
        NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection: 0];

        [self.tableView selectRowAtIndexPath:indexPathForFirstRow animated:animationEnabledForInitialFirstRowSelect scrollPosition:UITableViewScrollPositionTop];
    }
}

/* More Objective-C... */

@end

回答by jkyin

Here is my solution for swift 3.0:

这是我对 swift 3.0 的解决方案:

var selectedDefaultIndexPath = false


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if dataSource.isEmpty == false, selectedDefaultIndexPath == false {
        let indexPath = IndexPath(row: 0, section: 0)
        // if have not this, cell.backgroundView will nil.
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        // trigger delegate to do something.
        _ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath)
        selectedDefaultIndexPath = true
    }
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let cell = tableView.cellForRow(at: indexPath)
    cell?.selectedBackgroundView?.backgroundColor = UIColor(hexString: "#F0F0F0")

    return indexPath
}

回答by Michael Morrison

We use custom background images for the cell based on whether or not it is the first cell... a middle cell or the last cell. That way we get a nice rounded corner look to the whole table. When the row is selected, it swaps out a nice 'highlighted' cell to give the user feed back that they have selected a cell.

我们根据它是第一个单元格...中间单元格还是最后一个单元格为单元格使用自定义背景图像。这样我们就可以在整个桌子上获得漂亮的圆角外观。当该行被选中时,它会换出一个漂亮的“突出显示”单元格,让用户反馈他们已经选择了一个单元格。

UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];

if (row == 0 && row == sectionRows - 1)
{
    rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"];
    selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
    rowBackground = [UIImage imageNamed:@"topRow.png"];
    selectionBackground = [UIImage imageNamed:@"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
    rowBackground = [UIImage imageNamed:@"bottomRow.png"];
    selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"];
}
else
{
    rowBackground = [UIImage imageNamed:@"middleRow.png"];
    selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"];
}


((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;

If you wish just make the first cell, that which is at indexPath.row == 0, to use a custom background.

如果您只想制作第一个单元格(位于 indexPath.row == 0 的单元格)以使用自定义背景。

This is derived from Matt Gallagher's excellent site

这是源自 Matt Gallagher 的优秀网站

回答by Ashu

Swift 5.x Update:

Swift 5.x 更新:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let indexPath = IndexPath(row: 0, section: 0)
    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
    tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath)
}

This is working for me and hope this will helps you.

这对我有用,希望这会帮助你。

Happy Coding :)

快乐编码:)