【问题标题】:custom UISwitch won't change state自定义 UISwitch 不会改变状态
【发布时间】:2011-12-21 10:37:19
【问题描述】:

我有一个自定义的 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]; 

学生和课程都填好了。

【问题讨论】:

  • 您可能希望提供添加开关并调用它的代码。您将 UISwitch 子类化并将开关设置为实例变量 - 为什么? UISwitch 可能是您视图的一部分,不是吗?所以我想知道“学生”和“课程”是否适合这门课。
  • 我有点困惑 - 这是在 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]; Student 和 Course 可以填写。请您重述您的问题?
  • 检查将开关添加到视图的代码。它是您添加为子视图的“原始”开关吗?
  • 不——正如您从上面评论中的代码中看到的那样,我创建了一个 UISwitch,然后将它传递给我的自定义开关 initwithswitch 方法。然后,当它被创建时,我使用 customswitch.originalswitch 进入原始开关。
  • 然后你会写类似 [self.view addSubView:customswitch.originalswitch] 的东西吗?我自己也是这样做的。

标签: iphone ios5 uiswitch


【解决方案1】:

如果您在 ViewController 的 viewDidLoad 中这样调用它,您的代码将起作用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 2011-10-26
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2013-11-09
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多