【问题标题】:RubyMotion and UIPickerViewRubyMotion 和 UIPickerView
【发布时间】:2014-08-19 14:23:42
【问题描述】:

我想使用 UIPickerView 选择一个数字并将所选数字分配给一个标签。我想出了如何使用 ib gem 并使用界面生成器来创建初始界面,它工作正常。但是,我想纯粹使用 RubyMotion 代码来完成它,而且我一辈子都无法让它工作。我管理的最好的方法是让标签返回 True 而不是数字。

我正在为选取器视图委托方法使用以下标准代码:

def pickerView(pickerView, numberOfRowsInComponent:component)
  101
end

def pickerView(pickerView, titleForRow:row, forComponent:component)
  row.to_s
end

def numberOfComponentsInPickerView (pickerView)
  1
end

def pickerView(pickerView, didSelectRow:row, inComponent:component)

end

def pickerView(pickerView, titleForRow:row, forComponent:component)
  " #{row+1}"
end

def submit
  totals.addTotals(myPicker.selectedRowInComponent(0))
end

然后标签文本填充如下:

numLabel = UILabel.new
numLabel.text = "Number Selected:  #{submit}"
numLabel.font = UIFont.boldSystemFontOfSize(18)
numLabel.frame = [[20,320],[260,340]]
numLabel.numberOfLines = 2
numLabel.adjustsFontSizeToFitWidth = 'YES'
self.view.addSubview numLabel

总计是一个共享客户端。

【问题讨论】:

标签: rubymotion


【解决方案1】:

以下是仅在 RubyMotion 中执行此操作的方法。请注意,标签和选择器是在viewDidLoad 中设置的。标签在pickerView:didSelectRow:inComponent:中更新

app_delegate.rb

class AppDelegate
  def application(application, didFinishLaunchingWithOptions:launchOptions)
    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
    @window.rootViewController = PickerDemo.new
    @window.makeKeyAndVisible
    true
  end
end

picker_demo.rb

class PickerDemo < UIViewController
  def viewDidLoad
    view.backgroundColor = UIColor.whiteColor
    @numLabel = UILabel.new
    @numLabel.text = "Number Selected:  0"
    @numLabel.font = UIFont.boldSystemFontOfSize(18)
    @numLabel.frame = [[20,100],[260,120]]
    @numLabel.numberOfLines = 2
    @numLabel.adjustsFontSizeToFitWidth = true
    view.addSubview(@numLabel)

    @picker = UIPickerView.new
    @picker.frame = [[0, 183], [320, 162]]
    @picker.delegate = self
    @picker.dataSource = self
    view.addSubview(@picker)
  end

  def pickerView(pickerView, numberOfRowsInComponent:component)
    101
  end

  def pickerView(pickerView, titleForRow:row, forComponent:component)
    row.to_s
  end

  def numberOfComponentsInPickerView(pickerView)
    1
  end

  def pickerView(pickerView, didSelectRow:row, inComponent:component)
    @numLabel.text = "Number Selected:  #{row}"
  end
end

【讨论】:

  • 酷 - 如果可以的话,还有一个问题:我如何将选定的数字作为数字而不是字符串返回以用作计算目的的变量?
  • 只需使用 Ruby 的to_i 方法将字符串转为整数进行计算。在这种情况下,由于您的行号与该行上的标签匹配,因此只需在 didSelectRow 中使用 row 变量,因为它已经是一个整数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多