我正在对一对坐标进行反向地理编码以查找用户的城市,但很难将城市放入运动套件布局。让城市进入布局的最佳方式是什么?我还会将 API 中的其他信息添加到布局中,因此可能会遇到相同的问题。
有一个基本的 MK 布局,如下所示:
class HomeLayout < MK::Layout
def initialize(data)
@city = data[:city]
super
end
def layout
add UILabel, :location
end
def location_style
text @city
color :white.uicolor
font UIFont.fontWithName("Avenir", size: 22)
size_to_fit
center ['50%', 80]
end
end
我在HomeScreen
从这种方法中得到了@city
:
def city
loc = CLLocation.alloc.initWithLatitude App::Persistence['latitude'], longitude: App::Persistence['longitude']
geo = CLGeocoder.new
geo.reverseGeocodeLocation loc, completionHandler: lambda { |result, x|
return result[0].locality
}
# This currently returns a CLGeocoder object, but I want it to return the city as a String.
end
我从 AppDelegate 中的on_activate
中获取App::Persistence['latitude']
,如下所示:
def on_activate
BW::Location.get_once do |result|
if result.is_a?(CLLocation)
App::Persistence['latitude'] = result.coordinate.latitude
App::Persistence['longitude'] = result.coordinate.longitude
open HomeScreen.new
else
LocationError.handle(result[:error])
end
end
end
任何帮助将不胜感激。提前谢谢。
我必须看看您如何实例化布局,但即使没有它,我也有一个猜测:您应该考虑支持在数据可用时关闭的fetching location
消息。
工作流如下所示:
- 在不提供位置数据的情况下创建布局。 它将以"等待位置"状态启动
- 获取城市位置,就像您现在一样
- 提供布局的位置,它可以对视图更改进行动画处理
class HomeLayout < MK::Layout
def location(value)
# update view locations.
# you might also provide an `animate: true/false` argument,
# so that you can update the UI w/out animation if the
# location is available at startup
end
end
完成此操作后,您可以执行第二遍:在启动时提供城市数据。 如果数据可用,您应该能够像上面一样将其传递给初始值设定项,并且布局应绕过"加载"状态。
我推荐这种方法的原因是因为它使控制器更加"幂等"。 无论是否在启动时提供位置数据,它都可以处理这两种情况。
此外,您还可以在等待get_once
块完成之前open HomeScreen.new
。