《从零开始学iOS7开发系列3-我的地盘我做主-Cha8》.pdf
文本预览下载声明
从零开始学iOS7开发系列3-我的地盘我做主-Cha8
原⽂及⽰例代码来⾃raywenderlich store中的iOS Apprentice 系列3教程,经过翻译和改编。
版权归原作者所有,本系列教程仅供学习参考使⽤,感兴趣的朋友建议购买原英⽂教程教程(The
iOS Apprentice Second Edition: Learn iPhone and iPad Programming via Tutorials!)。
购买链接:
/store
没词了,欢迎继续我们的学习。
这⼀课我们将学习将位置坐标信息放到界⾯中。
刚才的didUpdateLocation代理⽅法向应⽤返回了⼀个CLLocation对象数组,每个CLLocation对象
都包含了⽤户的当前经度和纬度信息。这些对象其实还有其它属性信息,⽐如海拔⾼度和速度等,
不过在当前应⽤中我们暂时还⽤不到。
我们将使⽤数组中的最后⼀个CLLocation对象,因为它是最新的信息,并在界⾯的标签中显⽰坐标
信息。
打开Xcode ,在CurrentLocationViewController.m中添加⼀个新的实例变量_location
@implementation CurrentLocationViewController{
CLLocationManager *_locationManager;
CLLocation *_location;
}
我们将把⽤户的当前位置信息保存在这个变量⾥⾯。
更改didUpdateLocations⽅法的内容如下:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *newLocation = [locations lastObject];
NSLog(@ 已更新坐标,当前位置:%@,newLocation);
_location = newLocation;
[self updateLabels];
}
这⾥依然要保留NSLog()这⾏代码,因为它对后续的debugging调试会很有帮助。
在新添加的代码中,我们将所获取的最新位置信息保存在刚刚创建的实例变量中,然后调⽤给⼀个
updateLabels⽅法。
接下来添加updateLabels⽅法的实现代码:
-(void)updateLabels{
if(_location !=nil){
self.latitudeLabel.text = [NSString stringWithFormat:@%.8f,_location.coordinate.latitude];
self.longtitudeLabel.text = [NSString stringWithFormat:@%.
8f,_location.coordinate.longitude];
self.tagButton.hidden = NO;
self.messageLabel.text = @;
}else{
self.latitudeLabel.text = @;
self.longtitudeLabel.text = @;
self.adderssLabel.text = @;
self.tagButton.hidden = YES;
self.messageLabel.text = @Press the Button to Start;
}
}
下⾯解释下刚才的⽅法内容:
如果_location这个实例变量的内容不是nil ,也就是说存在⼀个最新的位置信息对象,那么就把它⾥
⾯的double类型的latitude和longtitude数值转换成strings字符串类型,然后把字符串的内容放到标
签中。stringWithFormat⽅法的%.8f格式符和之前的%f格式符作⽤类似,区别在于它会保留8位⼩数
这也是.8的作⽤所在。
编译运⾏应⽤,然后在Simulator的Debug菜单中选择⼀个
显示全部