【问题标题】:Using asynchronously obtained data in Motion-Kit layouts在 Motion-Kit 布局中使用异步获取的数据
【发布时间】:2014-12-03 18:09:43
【问题描述】:

我正在对一对坐标进行反向地理编码以找到用户所在的城市,但很难将城市置于 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

我从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

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

【问题讨论】:

    标签: ios rubymotion rubymotion-promotion


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2012-05-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多