样式iOS的条件数百分比

时间:2014-06-07 01:26:30

标签: ios objective-c percentage

我试图显示一个百分比标签,该标签会根据其价值设置一些风格。用户喜欢和不喜欢。这些总计显示在totalLikesLabel和totalDislikesLabel中。

我希望approvalPercentageLabel显示喜欢不喜欢的百分比。高于50%的文本将显示绿色,低于50%的文本将显示为红色。

当我记录[self.totalLikesLabel.text intValue]和[self.totalDislikesLabel.text intValue]时,它们显示为22和12.当它们当前都设置为1时。

@interface

@property (strong, nonatomic) IBOutlet UILabel *totalLikesLabel;
@property (strong, nonatomic) IBOutlet UILabel *totalDislikesLabel;
@property (strong, nonatomic) IBOutlet UILabel *approvalPercentageLabel;

@property (nonatomic) int likeCount;
@property (nonatomic) int dislikeCount;

-viewDidLoad

self.likeCount = [self.totalLikesLabel.text intValue];
self.dislikeCount = [self.totalDislikesLabel.text intValue];

float approvalPercentage = (self.likeCount / (self.likeCount + self.dislikeCount)) * 100.0;
self.approvalPercentageLabel.text = [NSString stringWithFormat:@"%2.0f%%", approvalPercentage];

-helperMethod

//Create an Array to check either user photo
NSArray *userPhotos = @[self.firstUserPhoto, self.secondUserPhoto];

PFQuery *queryForLikes = [PFQuery queryWithClassName:kDDActivityClassKey];
[queryForLikes whereKey:kDDActivityTypeKey equalTo:kDDActivityTypeLikeKey];
[queryForLikes whereKey:kDDActivityFirstUserPhotoKey containedIn:userPhotos];
[queryForLikes whereKey:kDDActivitySecondUserPhotoKey containedIn:userPhotos];
[queryForLikes countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
    self.totalLikesLabel.text = [NSString stringWithFormat:@"%i", number];
    NSLog(@"Likes %i", number);
}];

PFQuery *queryForDislikes = [PFQuery queryWithClassName:kDDActivityClassKey];
[queryForDislikes whereKey:kDDActivityTypeKey equalTo:kDDActivityTypeDislikeKey];
[queryForDislikes whereKey:kDDActivityFirstUserPhotoKey containedIn:userPhotos];
[queryForDislikes whereKey:kDDActivitySecondUserPhotoKey containedIn:userPhotos];
[queryForDislikes countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
    self.totalDislikesLabel.text = [NSString stringWithFormat:@"%i", number];
    NSLog(@"Dislikes %i", number);
}];

1 个答案:

答案 0 :(得分:0)

我最终将此查询添加到辅助方法中。我收到警告:主线程上正在执行长时间运行的Parse操作,这样做不理想,否则它正在工作。

PFQuery *queryForApprovalPercent = [PFQuery orQueryWithSubqueries:@[queryForLikes, queryForDislikes]];
[queryForApprovalPercent countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
    if (!error) {
        [queryForLikes countObjects];
        self.likeCount = [queryForLikes countObjects];
        self.dislikeCount = [queryForDislikes countObjects];
        float approvalPercentage = (self.likeCount / (self.likeCount + self.dislikeCount)) * 100.0;
        self.approvalPercentageLabel.text = [NSString stringWithFormat:@"%2.0f%%", approvalPercentage];
        if (approvalPercentage < 5) self.approvalPercentageLabel.textColor = [UIColor redColor];
    }
}];