1

我正在对一对坐标进行反向地理编码以找到用户的城市,但很难将城市纳入 Motion-Kit 布局。将城市融入布局的最佳方式是什么?我还会将来自 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

@city从这个方法中得到HomeScreen

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

App::Persistence['latitude']on_activateAppDelegate 中获取,如下所示:

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

任何帮助,将不胜感激。提前谢谢。

4

1 回答 1

2

我必须看看你是如何实例化布局的,但即使没有,我也有一个猜测:你应该考虑支持一条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

完成此操作后,您可以进行第二次操作:在启动时提供城市数据。如果数据可用,您应该能够像上面一样将其传递给您的初始化程序,并且布局应该绕过“加载”状态。

我推荐这种方法的原因是因为它使控制器更加“幂等”。无论是否在启动时提供位置数据,它都可以处理这两种情况。

此外,您可以open HomeScreen.new在等待get_once块完成之前完成。

于 2014-12-04T16:45:42.680 回答