我正在尝试使用ReactiveCocoa和MVVM模式进行编码,并且我正在尝试设置一个自定义UITableViewCel
l,以便在相应的viewModel
获取新模型对象时更新其标签。
单元测试正在通过,所以我知道到目前为止视图模型本身正在工作。但我没有让UILabel
更新它们的属性文本。
这是我的UITableViewCellModel
:代码
@interface GYMWorkoutTableViewCellModel : NSObject
@property(nonatomic, copy, readonly) NSAttributedString *workoutName;
@property(nonatomic, copy, readonly) NSAttributedString *numberOfExercises;
@property(nonatomic, strong) GYMWorkout *workout;
@end
@implementation GYMWorkoutTableViewCellModel
- (id)init {
self = [super init];
if (!self) return nil;
RACSignal *newWorkoutSignal = [RACObserve(self, workout) ignore:nil];
RAC(self, workoutName) = [newWorkoutSignal map:^id(GYMWorkout *workout1) {
return [[NSAttributedString alloc] initWithString:workout1.name];
}];
RAC(self, numberOfExercises) = [newWorkoutSignal map:^id(GYMWorkout *workout2) {
NSString *numberOfExercisesString = [@([workout2.exercises count]) stringValue];
return [[NSAttributedString alloc] initWithString:numberOfExercisesString];
}];
return self;
}
@end
这是细胞本身的代码:
@interface GYMWorkoutTableViewCell : UITableViewCell
@property(nonatomic, strong) IBOutlet UILabel *workoutNameLabel;
@property(nonatomic, strong) IBOutlet UILabel *numberOfExercisesLabel;
@property(nonatomic, strong) GYMWorkoutTableViewCellModel *viewModel;
@end
@implementation GYMWorkoutTableViewCell
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (!self) return nil;
self.viewModel = [GYMWorkoutTableViewCellModel new];
RAC(self.workoutNameLabel, attributedText) = RACObserve(self, viewModel.workoutName);
RAC(self.numberOfExercisesLabel, attributedText) = RACObserve(self, viewModel.numberOfExercises);
return self;
}
@end
我正在根据视图控制器的tableView:cellForRowAtIndexPath:
方法中设置锻炼属性,如下所示:
GYMWorkoutTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"WorkoutCellIdentifier" forIndexPath:indexPath];
GYMWorkout *workout = [self.viewModel workoutAtIndexPath:indexPath];
cell.viewModel.workout = workout;
return cell;
有人能告诉我为什么GymWorkoutTableViewCell
中的RAC()
绑定不更新UILabel
吗?
编辑
当我将initWithCoder:
方法中的代码更改为时
[RACObserve(self, viewModel.workout) subscribeNext:^(GYMWorkout *gymWorkout) {
self.workoutNameLabel.text = gymWorkout.name;
}];
则CCD_ 10s的文本被改变。但这与该模型的需求背道而驰。
好吧-我想好了。initWithCoder:中所有为nil的标签:-所以我不得不推迟RAC((绑定,直到从nib加载所有内容。
- (void)awakeFromNib {
[super awakeFromNib];
RAC(self.workoutNameLabel, text) = RACObserve(self, viewModel.workoutName);
RAC(self.numberOfExercisesLabel, text) = RACObserve(self, viewModel.numberOfExercises);
}
现在标签更新了:(。