UITable из NSArray и огткрыть Detail

Рейтинг: 1Ответов: 1Опубликовано: 07.04.2015

Подскажите, бьюсь уже неделю, как при нажатии на cell сделать так что бы открывалось detailview.

NSArray *MyArray = @[@"привет мир1",@"привет мир2",@"привет мир3"];

Я открываю storyboard, добавляю новую view, создаю связь при помощи push (deprecated) вписываю id в storyboard segue, а вот что дальше? Ни как не могу найти код для новичков по созданию такой связки.

PS На всякий случай выкладываю свой код полностью

    static NSString *cellIdentifier;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    _startLocation = newLocation;
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{/* Не удалось получить информацию о местоположении пользователя. */
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([CLLocationManager locationServicesEnabled]){
        self.myLocationManager = [[CLLocationManager alloc] init];
        self.myLocationManager.delegate = self;
        [self.myLocationManager startUpdatingLocation];
        CLLocation *startLocation = self.myLocationManager.location;
        CLLocation *location2 = [[CLLocation alloc] initWithLatitude:60.050043 longitude:30.345783];
        CLLocation *location3 = [[CLLocation alloc] initWithLatitude:60.040000 longitude:30.323994];
        CLLocation *location4 = [[CLLocation alloc] initWithLatitude:60.037389 longitude:30.322094];
        float betweenDistance=[startLocation distanceFromLocation:location2];
        float betweenDistance3=[startLocation distanceFromLocation:location3];
        float betweenDistance4=[startLocation distanceFromLocation:location4];
        NSArray *stringsArray2 = @[
                                   [NSString stringWithFormat:@"Distance is %f km",betweenDistance/1000],
                                   [NSString stringWithFormat:@"Distance is %f km",betweenDistance3/1000],
                                   [NSString stringWithFormat:@"Distance is %f km", betweenDistance4/1000]
                                   ];
        NSString * combinedStuff = [stringsArray2 componentsJoinedByString:@"\n"];
    [GMSServices provideAPIKey:@"AIzaSyBdzbOnbi6GaoqUUJOC6f9XR3k5e5V77b0"];
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:59.93 longitude:30.35 zoom:9];
        mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
        mapView_.settings.compassButton = YES;
        mapView_.settings.myLocationButton = YES;
        //mapView_.settings.myLocationButton = YES;
        //mapView_.userInteractionEnabled = YES;
        mapView_.frame = CGRectMake(0, 0, 200, 200);
        //mapView_.center = self.view.center;
        [self.scrollView addSubview:mapView_];
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 210)];
        self.data = @[
                      [NSString stringWithFormat:@"Distance is %f km",betweenDistance/1000],
                      [NSString stringWithFormat:@"Distance is %f km",betweenDistance3/1000],

                      [NSString stringWithFormat:@"Distance is %f km", betweenDistance4/1000]
                      ];
    cellIdentifier = @"rowCell";
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
    } else {
        /* Геолокационные службы не активизированы.
         Попробуйте исправить ситуацию: например предложите пользователю
         включить геолокационные службы. */
        NSLog(@"Location services are not enabled");
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.textLabel.text = [self.data objectAtIndex:indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"My title" message:[NSString stringWithFormat:@" %@",[self.data objectAtIndex:indexPath.row],[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 210)]] delegate:self cancelButtonTitle:@"Close window" otherButtonTitles:nil];
    [message show];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

Ответы

▲ 1Принят

Вариант 1 В методе - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath необходимо по имени вызвать переход, вот так:

[self performSegueWithIdentifier:@"segueName" sender:self];

где segueName - имя вашего перехода.

Так же необходимо в контроллере реализовать метод - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender.

Этот метод вызывается для всех переходов. В нем можно понять для какого перехода был вызван метод сравнив имя перехода и можно настроить detailview - segue.destinationViewController:

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueName"]) {
        // Код по настройки segue.destinationViewController
    }
}

Вариант 2 Вы наверно в InterfaceBuilder сделали переход от контроллера, но можно сделать переход от ячейки на нажатие. Тогда не надо будет при нажатии на ячейку, из кода вызывать переход. Для этого надо в InterfaceBuilder потянуть связь от прототипа ячейки на нужный контроллер и в списке "selection segue" выбрать нужный переход.