从另一个ViewController类调用函数

时间:2011-09-03 12:16:51

标签: iphone uiviewcontroller uitableview

我有一个名为“CortesViewController”的ViewController,它有一个MKMapView Called mymap。我有一个函数showAddress,它在CortesViewController.h中定义并在相应的.m文件中实现。

- (void) showAddress:(float) lat :(float) lon :(int) keytype
{
centerCoordinate.latitude = lat;
    centerCoordinate.longitude = lon ;
        NSLog(@"with key = 0, lat lon are %f, %f", centerCoordinate.latitude, centerCoordinate.longitude);
    [mymap setCenterCoordinate:centerCoordinate animated:TRUE] ;
}

我有另一个UitableViewController“PlacesViewController”,其中包含名称和纬度和经度的地方列表,可以通过放置在CortesViewController上的按钮来显示。当点击任何地方的名字时,我想返回到mymap,显示地图中心的选定位置。所以我正在调用“showAddress”函数

     - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
PlaceViewController.m中的

。实施如下所示。

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    Place *placeAtIndex = (Place *)[appDelegate.PlacesArray objectAtIndex:indexPath.row];

    NSLog(@"required lat long is %f, %f ", placeAtIndex.PlaceLatitude, placeAtIndex.PlaceLongitude);


    CortesViewController *returnToMap = [[CortesViewController alloc] init];



    float tableLatitude = placeAtIndex.PlaceLatitude ;
    float tableLongitude = placeAtIndex.PlaceLongitude;
    [returnToMap showAddress :tableLatitude :tableLongitude : 0];   

    [self.navigationController dismissModalViewControllerAnimated:YES];
    }

代码运行时没有错误或警告,但是尽管点击了具有不同纬度和经度的地方,mymap中的视图也不会改变。 showAddress正确存储在PlaceViewController.m中的UITableView中的输入值lat,lon。但行

[mymap setCenterCoordinate:centerCoordinate animated:TRUE] ;

调用时似乎不起作用

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

请帮忙。感谢您提前提供任何帮助。

2 个答案:

答案 0 :(得分:1)

您似乎正在更改此行中的某些值

[returnToMap showAddress :tableLatitude :tableLongitude : 0];

如果在showAddress中您也正在更改视图,那么它可能无法反映某些情况下的更改(请参阅iOS中的线程和UI组件交互的详细信息)。

因此,我建议你只需在showAddress中更改变量,并在视图中相应地应用更改,即在CortesViewController的viewWillAppear方法中

如果以上情况不适用于您的情况,请在此处发布,以便我能够详细了解问题。

答案 1 :(得分:0)

didSelectRowAtIndexPath中,您正在创建CortesViewController的新实例,该实例与呈现PlaceViewController的实例无关。

您应该在提交时将CortesViewController的引用传递给PlaceViewController,或者您可以使用NSNotificationCenterCortesViewController发送消息,或者(可能是最好的) )使用委托+协议发回CortesViewController

此外,不是您的问题,但showAddress的定义不符合惯例。您没有命名参数。而不是:

- (void) showAddress:(float) lat :(float) lon :(int) keytype

我建议:

- (void) showAddressWithLat:(float)lat Lon:(float) lon KeyType:(int) keytype

然后你会这样称呼它:

[returnToMap showAddressWithLat:tableLatitude Lon:tableLongitude KeyType:0];