开发者

Problem drawing in custom UIView class

开发者 https://www.devze.com 2022-12-18 20:09 出处:网络
I have a UIView subclass that has the following in drawRect: for(int j=0; j<[myArray count]; j++){ if([myArray objectAtIndex:j]!=@\"\"){

I have a UIView subclass that has the following in drawRect:

for(int j=0; j<[myArray count]; j++){
    if([myArray objectAtIndex:j]!=@""){    
        [[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1] set];
        CGContextFillRect(context, CGRectMake(55+(20*j),10,15,5));
        [[UIColor blackColor] set];
        [[myArray objectAtIndex:j] drawAtPoint:CGPointMake(55+(20*j),3+) withFont:myFont];
    }
}

I've logged inside the if statemen开发者_开发问答t and it works, but for some reason I still get drawn CGContextFillRects at every iteration of the loop, even when my current array object is @"".

I'm fairly new to drawing, so please excuse me if I'm missing something huge and trivial.


You can't test for equality with == or != when using objects; you need to use -isEqualTo:. For example:

for(int j=0; j<[myArray count]; j++){
    if(![[myArray objectAtIndex:j] isEqualTo: @""]){    
        [[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1] set];
        CGContextFillRect(context, CGRectMake(55+(20*j),10,15,5));
        [[UIColor blackColor] set];
        [[myArray objectAtIndex:j] drawAtPoint:CGPointMake(55+(20*j),3+) withFont:myFont];
    }
}

Each object in your array is a pointer to memory. Even if two objects have the same logical contents (such as an empty string), they most likely point to different chunks of memory. What you want to do is compare the contents of those memory chunks, which is what -isEqualTo: does.


if (![[myArray objectAtIndex:j] isEqualToString:@""]) {

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号