Search code examples
iosobjective-ccalayer

Border of each UIView


enter image description here

I have to create something similar to above mentioned image. I have a view and i need border after eat view like {breakfast, brunch,etc..}

for giving border I was have following code.

CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, 43.0f, menuHeadView.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor colorWithWhite:0.8f
                                                 alpha:1.0f].CGColor;
[menuHeadView.layer addSublayer:bottomBorder];

it works fine for single view but if I have an array for those views and I want to have border after each view using indexPath it doesn't work since it doesn't allow

[array objectAtIndex:i].layer;

help please! Thanks in advance.


Solution

  • If you have array of views you probably should cast: Change :

    [array objectAtIndex:i].layer;
    

    To:

    ((UIView*)[array objectAtIndex:i]).layer;
    

    EDIT: Based on @Mischa comment:

    Casting is telling the array what object is in it. If you have different kind of objects in array (you really shouldn't!) or to be super safe you can change casting to assign:

    id myUnknownObject = [array objectAtIndex:i];
    if([myUnknownObject isKindOfClass:[UIView class]]) {
       ((UIView*)myUnknownObject).layer...
    } else {
       NSLog(@"%@",[myUnknownObject class]);
    }
    

    But base on your comment you contain NSStrings in your array so you can't add layer to this objects. Please check your console, it's probably NSString.

    Of course since you mentioned indexPath, and if you're using TableView with rows. You should use the good stuff from reusability and it method:

    -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        NSDictionary *cellDic = [self.heartbeats objectAtIndex:indexPath.row];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            //here goes reusability part like styling and stuff, this will calling only once for every reusable cell. So for example for cells height 44 this will called only 13 times for iPhone screen.
    
           //HERE you should manipulate with layer!
        }
        //here goes your custom text of every cell - like "Breakfast", "Brunch" and so on. This will calls for every row which is about to show up. 
    
          //HERE you should manipulate with text
    
        return cell;
    }