developer tip

UITableView에서 첫 번째 행을 기본값으로 선택하십시오.

optionbox 2021. 1. 10. 17:08
반응형

UITableView에서 첫 번째 행을 기본값으로 선택하십시오.


뷰 기반 응용 프로그램이 있고 테이블 뷰를 기본 뷰에 하위 뷰로 추가하고 있습니다. 나는 UITableViewDelegate테이블 방법에 응답했습니다. 모든 것이 잘 작동하지만 첫 번째 행을 선택하거나 UITableView기본값으로 선택 (강조 표시) 하고 싶습니다 .

필요한 코드와 코드를 어디에 넣어야하는지 도와주세요.


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

코드에서이를 사용하는 가장 좋은 방법은 기본적으로 행을 선택하려는 경우 viewDidAppear에서 사용하는 것입니다.


Swit 3.0 업데이트 된 솔루션

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

- (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];
    }

- (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];
    }
}

Swift 1.2에서이를 수행하는 방법은 다음과 같습니다.

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

Swift 4 업데이트 :

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

다른 섹션에서 다른 행을 선택하려면 행 및 섹션 값을 변경하십시오.


테이블이 처음로드 될 때 첫 번째 셀만 선택하려면 using viewDidLoad이 올바른 위치 라고 생각할 수 있지만 실행 당시에는 테이블이 해당 내용을로드하지 않았으므로 작동하지 않습니다 (그리고 NSIndexPath존재하지 않는 셀을 가리 키 므로 앱이 중단 될 수 있습니다.)

해결 방법은 테이블이 이전에로드되었음을 나타내는 변수를 사용하고 그에 따라 작업을 수행하는 것입니다.

@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

다음은 신속한 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
}

셀이 첫 번째 셀 ... 중간 셀인지 마지막 셀인지 여부에 따라 셀에 사용자 지정 배경 이미지를 사용합니다. 이렇게하면 전체 테이블에 멋진 둥근 모서리가 생깁니다. 행이 선택되면 멋진 '강조 표시된'셀을 교체하여 사용자가 셀을 선택했다는 피드백을 제공합니다.

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.

This is derived from Matt Gallagher's excellent site


You can do like this:

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

ReferenceURL : https://stackoverflow.com/questions/2728152/select-first-row-as-default-in-uitableview

반응형