Question

I am trying to implement a custom layout for three views. The views are used for Categories which are "Bars", "Clubs" and "Food".

Each of these categories will have it own custom circle view. Within the circle view will be a label that has the text in.

Current Setup
At present the three views are added to the Storyboard, and given the relevant UIView subclass. The subclass then handles making them circle and adding the label.

- (id)init {
    self = [super init];
    if (self) {
        [self setupView];
    }
    return self; }

-(void)setupView {
    self.translatesAutoresizingMaskIntoConstraints = NO;
    float newRadius = self.frame.size.width/2;
    self.layer.cornerRadius = newRadius; // TODO / TEST - The UIImageView is set to 40x40 and the frame is yet to be created
    self.layer.masksToBounds= YES;

    self.layer.borderWidth = 5;
    self.layer.borderColor = [UIColor colorWithRed:0.138 green:0.225 blue:1.000 alpha:1.000].CGColor;


    self.backgroundColor = [self randomColor];

    [self setupLabel];
}

-(void)setupLabel {
    UILabel *label = [[UILabel alloc]init];
    label.translatesAutoresizingMaskIntoConstraints = NO;
    label.text = @"Test";
    label.textColor = [UIColor whiteColor];
    label.text = [label.text uppercaseString];
    [self addSubview:label];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
}

However, with the above setup I cannot think how I would implement each circle view with different label text?

What is the best way to handle this custom view and layout. Would it be better to have the circle views created completely in code and change the custom init method to pass a NSString for the label instead?

Was it helpful?

Solution

You can create a property called text in your custom UIView and then use User Runtime Attributes to change it.

In the Interface Builder you can have:

enter image description here

Then you can override in your CustomView:

// This method will get called for each attribute you define.
-(void) setValue:(id)value forKey:(NSString *)key {
    if ([key isEqualToString:@"text"]) {
        self.mylabel.text = value;
    }
}

Note that you need to have your label in a property. @property (nonatomic, weak) UILabel* myLabel So, when you setup your label you would need to :

-(void)setupLabel {
    UILabel *label = [[UILabel alloc]init];
    //...
    [self addSubview:label];

    //the label, since it is weak, needs to be added to the visual tree first
    self.myLabel = label;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top