自定义UISwitch不会改变状态

时间:2011-12-21 10:37:20

标签: iphone ios5 uiswitch

我有一个自定义的uiswitch类,没什么特别的,标题看起来像这样:

#import <Foundation/Foundation.h>

@class Course;
@class Student;

@interface AttandanceSwitch : UISwitch

@property (strong,nonatomic) Course *course;
@property (strong,nonatomic) Student *student;
@property (strong,nonatomic) UISwitch *originalSwitch;

-(id)initWithSwitch:(UISwitch *)newSwitch Student:(Student *)student andCourse:(Course *)course;
-(NSString *) description;

@end
<。> .m文件如下所示:

#import "AttandanceSwitch.h"
#import "Course.h"
#import "Student.h"

@implementation AttandanceSwitch 

@synthesize course,student,originalSwitch;

-(id)initWithSwitch:(UISwitch *)newSwitch Student:(Student *)studentP andCourse:(Course *)courseP
{

    self = [super init];
    self.course = courseP;
    self.student = studentP;
    self.originalSwitch = newSwitch;

    [self.originalSwitch setOn:YES];

    return self;
}

-(NSString *) description 
{
    return [NSString stringWithFormat:@"Student: %@, Course: %@, Switch: %@",student.name,course.name,[originalSwitch description]];
}

@end

实际上是什么问题 - 当我使用initWithSwitch创建这个类的新对象时,我无法设置originalSwitch值。我甚至尝试静态设置它(参见self.originalSwitch setOn:YES上面),但即使我这样做,开关仍然关闭。

非常感谢任何关于如何使这项工作的想法...

这是在tableviewcell中使用此类的摘录:

UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero]; 
[switchView addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventTouchUpInside]; 
AttandanceSwitch *customSwitch = [[AttandanceSwitch alloc] initWithSwitch:switchView Student:student andCourse:courseToTrack]; 

学生和课程充满了好处。

1 个答案:

答案 0 :(得分:0)

如果您在ViewController的viewDidLoad中调用它,您的代码将会正常工作:

UISwitch *newSwitch = [[UISwitch alloc] init];
AttandanceSwitch *customSwitch = [[AttandanceSwitch alloc] initWithSwitch:newSwitch];
[self.view addSubView:customSwitch.original];
[customSwitch.original setOn:YES];