【问题标题】:disable particular rows in custom picker禁用自定义选择器中的特定行
【发布时间】:2011-12-13 06:16:23
【问题描述】:

我正在开发一个应用程序,它显示具有以下值的选择器: 1.早上 2.中午 3.晚上

根据当前时间,我需要显示各自的值。

说如果它是下午 3 点,用户应该只能选择晚上。

现在我的问题是,有什么方法可以让“早上和中午”无法选择。类似于日期选择器我可以将选项变灰吗?用户应该知道所有选项,但他应该能够根据时间选择选项。

提前致谢。

【问题讨论】:

  • 为什么不在用户完成选择值时显示一个警报视图,并将选择器动画恢复到其原始值。
  • 如果用户只能选择其中一个选项,为什么还要将所有选项都提供给用户呢?这很奇怪。
  • sara 和 ankit ,这是我的要求。它应该可用但不可选择。

标签: iphone ios ipad uipickerview


【解决方案1】:

如果您想在选取器视图中灰显某些值,请使用以下委托 API 覆盖该位置的视图。

 - (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component

创建一个 UILabel 并将其文本颜色设置为灰色并将其作为上面的视图返回。

如果选择了灰色文本,则通过调用以下 API 将动画设置为默认选择。

 - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated;

希望这会有所帮助。

【讨论】:

  • 在这个方法中 -- (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)componen;如果我创建一个灰色的标签不会所有行都是灰色的???我想要几行灰色(不可选择)和几行黑色(可选行)
  • 好的。由于您同时获得了组件(NSInteger)和行(NSInteger)值,因此您可以根据这些值将不可选择的项目变灰并涂黑。
【解决方案2】:

要使选取器中的行变灰,有一个比创建自己的视图更简单的解决方案。那就是使用属性TitleForRow。

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?

因为如果您返回 nil,此函数将回退到 titleForRow,您可以为禁用的行返回灰色,并使用标准的 titleForRow 返回其余的行。举个例子:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    // Need to provide the below function isRowDisabled that returns true as needed
    if isRowDisabled(row:row) {
        let attributes = [NSAttributedStringKey.foregroundColor: UIColor.gray]
        let str = NSAttributedString(string: "my gray text on row \(row)", attributes:attributes)
        return str
    } else {
        return nil
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return "my normal text on row \(row)"
}

然后,您必须忽略其他回复中提到的禁用行的 didSelectRow。

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 2012-08-28
    相关资源
    最近更新 更多