使用标签从UISliders获取值

时间:2014-07-25 09:20:07

标签: objective-c tags slider

简介

我创建了一堆带循环的滑块。我现在想要在按下按钮时检索它们的值。似乎有一些问题导致应用程序崩溃,我不确定出了什么问题

代码

定义滑块标记

slider1.tag = count;
count += 1;  
[subView addSubview:slider1];

检索滑块值

-(void) build:(id)sender {
    for (int i = 0; i < count; i++){
        UISlider *Slider = (UISlider*)[self.view viewWithTag:i];
        NSLog(@"%f",Slider.value);
    }
}

日志

我猜这意味着找不到滑块,但为什么会这样?

  

2014-07-25 17:18:49.911 App1.0 [5155:a0b] - [UIView value]:无法识别   选择器发送到实例0x109a44f00

     

2014-07-25 17:18:49.913 App1.0 [5155:a0b] *由于终止应用   未被捕获的异常&#39; NSInvalidArgumentException&#39;,原因:&#39; - [UIView   value]:无法识别的选择器发送到实例0x109a44f00&#39;   * 第一次抛出调用堆栈:(0 CoreFoundation 0x0000000101ae8795 exceptionPreprocess + 165 1 libobjc.A.dylib
  0x000000010184b991 objc_exception_throw + 43 2 CoreFoundation
  0x0000000101b79bad - [NSObject(NSObject)doesNotRecognizeSelector:] +   205 3 CoreFoundation 0x0000000101ada09d   ___转发_
+ 973 4 CoreFoundation 0x0000000101ad9c48 _CF_forwarding_prep_0 + 120 5 Dream1.0
  0x0000000100001d8d - [TemplateViewController build:] + 173 6 UIKit
  0x00000001004af096 - [UIApplication sendAction:to:from:forEvent:] + 80     7 UIKit 0x00000001004af044    - [UIApplication sendAction:toTarget:fromSender:forEvent:] + 17 8 UIKit 0x0000000100583450 - [UIControl   _sendActionsForEvents:withEvent:] + 203 9 UIKit 0x00000001005829c0 - [UIControl touchesEnded:withEvent:] + 530 10   UIKit 0x00000001007b3c3d   _UIGestureRecognizerUpdate + 5149 11 UIKit 0x00000001004e3925 - [UIWindow _sendGesturesForEvent:] + 928 12 UIKit   0x00000001004e45e5 - [UIWindow sendEvent:] + 910 13 UIKit
  0x00000001004bdfa2 - [UIApplication sendEvent:] + 211 14 UIKit
  0x00000001004abd7f _UIApplicationHandleEventQueue + 9549 15   CoreFoundation 0x0000000101a77ec1    CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17 16 CoreFoundation 0x0000000101a77792   __CFRunLoopDoSources0 + 242 17 CoreFoundation 0x0000000101a9361f __CFRunLoopRun + 767 18 CoreFoundation
  0x0000000101a92f33 CFRunLoopRunSpecific + 467 19 GraphicsServices
  0x000000010311b3a0 GSEventRunModal + 161 20 UIKit
  0x00000001004ae043 UIApplicationMain + 1010 21 Dream1.0
  0x0000000100005903 main + 115 22 libdyld.dylib
  0x0000000103dc37e1 start + 0)libc ++ abi.dylib:终止于   NSException(lldb)

类型的未捕获异常

1 个答案:

答案 0 :(得分:0)

这是因为您的viewWithTag:每次都不会返回UISlider。 在第一次循环迭代中:

for (int i = 0; i < count; i++){

i等于0且0是默认值,因此您没有更改标签属性的每个UIView子类都将该值设置为0,例如您按下的按钮。

其中一个解决方案是将你的UISlider标签设置为1而不是0,当你检索滑块时你应该从1枚举,你也应该做安全检查以确保你有UISlider:

//计数的第一个值应为1,而不是0: //您可以在init方法中或循环计数= 1之前设置它;

slider1.tag = count;
count += 1;  
[subView addSubview:slider1];

-(void) build:(id)sender {
    for (int i = 1; i <= count; i++){
        UIView *v = [self.view viewWithTag:i];
        if ([v isKindOfClass:[UISlider class]) {
            UISlider *Slider = (UISlider*)v;
            NSLog(@"%f",Slider.value);
        }
    }
}