Search code examples
iphoneobjective-cuitableviewalphabet

Adding vertical alphabets selector in UIView


Hi Can I add the vertical alphabets selector thing like that we use in UITableView, in UIView? Best Regards


Solution

  • Yes.

    If you create the UIView yourself you can do whatever you want.

    It's not even that hard in your case. Some UILabels as subviews and some logic in touchesDidSomething:withEvent: to figure out which label is near the touch.

    And a delegate method that tells which section was touched.


    I think I could need something like that, so I decided to try it.

    //myIndexSelectorView.m
    
    - (id)initWithFrame:(CGRect)frame andLabels:(NSArray *)l {
        self = [super initWithFrame:frame];
        if (self) {
            self.backgroundColor = [UIColor lightGrayColor];
            self.layer.cornerRadius = frame.size.width/2;
            labels = [l retain];
            NSInteger count;
            for (NSString *string in labels) {
                CGFloat margin = 5.0f;
                CGFloat yPosition = count*(frame.size.height/[labels count]);
                UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(margin, yPosition, frame.size.width-2*margin, frame.size.height/[labels count])] autorelease];
                label.backgroundColor = [UIColor clearColor];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = UITextAlignmentCenter;
                label.text = string;
                [self addSubview:label];
                count++;
            }
        }
        return self;
    }
    
    - (void)touch:(UITouch *)touch {
        CGPoint touchPosition = [touch locationInView:self];
        NSInteger index = touchPosition.y / (self.bounds.size.height / [labels count]);
        NSLog(@"Touched: %@", [labels objectAtIndex:index]);
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        [self touch:touch];
    }
    
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        [self touch:touch];
    }
    
    - (void)dealloc {
        [labels release];
        [super dealloc];
    }
    

    works as expected and looks similar to the index selector of uitableview

    enter image description here

    as usual, I didn't check for bugs, and this should not be a copy&paste solution.