【问题标题】:Slider with real time in Label标签中的实时滑块
【发布时间】:2011-12-26 14:54:36
【问题描述】:

我需要一个滑块,用于在滑块标签中显示从上午 12 点到晚上 11 点到 45 点的实时时间,步长为 15 分钟。但我只是不知道该怎么做。有人可以给我一些建议吗?

【问题讨论】:

    标签: iphone objective-c ios ipad uislider


    【解决方案1】:

    如果您只需要一个带滑块的时间选择器,请在sliderChanged中使用以下代码:处理程序:

    - (IBAction)onSliderChange:(id)sender {
    
        UISlider *slider = (UISlider *)sender;
    
        NSUInteger numberOfSlots = 24*4 - 1; //total number of 15mins slots
    
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"h-mm a"];
    
        NSDate *zeroDate = [dateFormatter dateFromString:@"12-00 AM"];
    
        NSUInteger actualSlot = roundf(numberOfSlots*slider.value);
        NSTimeInterval slotInterval = actualSlot * 15 * 60;
    
        NSDate *slotDate = [NSDate dateWithTimeInterval:slotInterval sinceDate:zeroDate];
        [dateFormatter setDateFormat:@"h-mm a"];
    
        self.timeLabel.text = [dateFormatter stringFromDate:slotDate];
    }
    

    【讨论】:

    • 你好@Denis,如何从设备设置中为 24 小时格式执行此操作,我的意思是如果用户选择 24 小时格式,此逻辑不起作用。
    • 好吧,这当然不会自动工作,因为它以日期格式硬编码以包含 AM/PM 符号。但是,您可以稍微扩展示例中的逻辑,并支持 2 种不同的格式,具体取决于您的系统是使用 AM/PM 还是 24h 格式。要检测你可以使用例如this approach
    • @Denis,有没有其他方法可以执行
    • 对不起,我没明白,你说的“其他方式”是什么意思
    • 只需存储/恢复slider.value属性并手动调用onSliderChange:
    【解决方案2】:

    创建一个滑块,在视图控制器中,让滑块随着滑块上的值的变化而改变标签。要设置值的范围,请更改情节提要中属性下的范围(您也可以将更改间隔设置为 15 步)。您可能想给它以分钟或类似的时间间隔,然后将其转换为时间:)

    - (IBAction)sliderChanged:(UISlider *)sender
    

    【讨论】:

    • 我需要用户通过滑动滑块选择的时间值,这个时间应该在用户的标签中。
    【解决方案3】:

    我正在添加另一个答案来添加代码。是的,您可以从滑块中获取值,然后在将值转换为时间后设置标签的文本。像这样:

    // Add 0.5 to slider value and truncate it to an integer by type casting it as integer
    int sliderIntValue = (int)([sender value] + 0.5f);
    
    //do some conversion and set the label to the value
    
    self.sliderLabel.text = newLabelText;
    

    【讨论】:

      【解决方案4】:

      您可以使用NSTimer 每 15 分钟调用一次方法,并将滑块/标签更新为当前时间。

      您可能想查看NSDateFormatter,获取适合您日期的字符串表示形式可能很有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-24
        相关资源
        最近更新 更多