Question

I'm writing a method that changes an image and a var based on a touch position in an CGRect. I am currently manually inverting the touch position using a series of if statements. I'm not convinced this is a particularly efficient method of doing this.

It works ok for the image changing, but for the var changing (which I haven't implemented yet) I would need to scale from 1 – 100 in +1 increments.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];

    CGPoint point = [touch locationInView: self.view];
    if (CGRectContainsPoint(CGRectMake(0, 20, 117, 200), point)) {

    if (point.y >= 20 && point.y <= 32) //12
        imageA.image = [UIImage imageNamed:@"ChemA-15.png"];
    if (point.y >= 33 && point.y <= 45)
        imageA.image = [UIImage imageNamed:@"ChemA-14.png"];
    if (point.y >= 46 && point.y <= 58)
        imageA.image = [UIImage imageNamed:@"ChemA-13.png"];
    if (point.y >= 59 && point.y <= 70)
        imageA.image = [UIImage imageNamed:@"ChemA-12.png"];
    if (point.y >= 71 && point.y <= 82)
        imageA.image = [UIImage imageNamed:@"ChemA-11.png"];
    if (point.y >= 83 && point.y <= 94)
       imageA.image = [UIImage imageNamed:@"ChemA-10.png"];
    if (point.y >= 95 && point.y <= 106)
        imageA.image = [UIImage imageNamed:@"ChemA-9.png"];
    if (point.y >= 107 && point.y <= 118)
        imageA.image = [UIImage imageNamed:@"ChemA-8.png"];
    if (point.y >= 119 && point.y <= 130)
        imageA.image = [UIImage imageNamed:@"ChemA-7.png"];
    if (point.y >= 131 && point.y <= 142)
        imageA.image = [UIImage imageNamed:@"ChemA-6.png"];
    if (point.y >= 143 && point.y <= 154)
        imageA.image = [UIImage imageNamed:@"ChemA-5.png"];
    if (point.y >= 155 && point.y <= 166)
        imageA.image = [UIImage imageNamed:@"ChemA-4.png"];
    if (point.y >= 167 && point.y <= 178)
       imageA.image = [UIImage imageNamed:@"ChemA-3.png"];
    if (point.y >= 179 && point.y <= 190)
        imageA.image = [UIImage imageNamed:@"ChemA-2.png"];
    if (point.y >= 191 && point.y <= 202)
        imageA.image = [UIImage imageNamed:@"ChemA-1.png"];

    }
}

Is there a better way to do this? Thanks for any help offered.

Was it helpful?

Solution

You can calculate what image you need like:

int image = 15 - (int)((point.y - 20) / 13);

and then make a string from it and check for bounds like:

if(image >= 1 && image <= 15)
    imageA.image = [UIImage imageNamed:
                    [NSString stringWithFromat: @"ChemA-%d.png", image]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top