kamran619
kamran619

Reputation: 531

Custom UIView Subclass background color not being set with Autolayout enabled

I am creating a subclass of UIView with AutoLayout and cannot get it's background color to change for the life of me. Can someone take a look at the simple code and verify I am doing everything that needs to be done in the subclass of the UIView(PCCGenericRatingView). I read on SO that setting the background color only works if the frame is set. Shouldn't it be setting my frame to something other than CGRectZero after evaluating the constraints? I am printing out the view's frame in the viewDidAppear: lifecycle method, but it appears to be CGRectZero.

Edit: When the frame is passed in to the views initWithFrame initializer, the background color is shown. Otherwise, it is now shown.

PCCGenericRatingView.h file:

#import <UIKit/UIKit.h>

@interface PCCGenericRatingView : UIView

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;

- (instancetype)initWithTitle:(NSString *)title andMessage:(NSString *)message;
+ (instancetype)genericRatingViewWithTitle:(NSString *)title andMessage:(NSString *)message;

@end

PCCGenericRatingView.m file:

#import "PCCGenericRatingView.h"

@implementation PCCGenericRatingView

- (instancetype)initWithTitle:(NSString *)title andMessage:(NSString *)message {
    if (self = [super init]) {
        self.titleLabel = [[UILabel alloc] init];
        self.messageLabel = [[UILabel alloc] init];

        _titleLabel.text = title;
        _messageLabel.text = message;

        [self customizeView];
    }

    return self;
}

- (void)customizeView {
    [self addSubview:_titleLabel];
    [self addSubview:_messageLabel];

    [_titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
    [_messageLabel setTranslatesAutoresizingMaskIntoConstraints:NO];

    [_titleLabel setBackgroundColor:[UIColor yellowColor]];
    [_messageLabel setBackgroundColor:[UIColor yellowColor]];

    [_messageLabel setNumberOfLines:0];

    [_messageLabel setTextAlignment:NSTextAlignmentCenter];
    [_titleLabel setTextAlignment:NSTextAlignmentCenter];

    [_titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:24.0f]];
    [_messageLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Thin" size:18.0f]];
}

+ (instancetype)genericRatingViewWithTitle:(NSString *)title andMessage:(NSString *)message {
    return [[PCCGenericRatingView alloc] initWithTitle:title andMessage:message];
}

+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}

- (BOOL)translatesAutoresizingMaskIntoConstraints {
    return NO;
}

-(void)updateConstraints {

     CGRect windowRect = [UIScreen mainScreen].bounds;
     NSDictionary *metrics = @{
     @"height" : @(windowRect.size.height),
     @"width"  : @(windowRect.size.width)
     };

    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(self);

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[self(==width)]" options:0 metrics:metrics views:viewsDictionary]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[self(==height)]" options:0 metrics:metrics views:viewsDictionary]];


    [self addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel
                                                     attribute:NSLayoutAttributeTop
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeTop
                                                    multiplier:1.0f
                                                      constant:35.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel
                                                     attribute:NSLayoutAttributeCenterX
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeCenterX
                                                    multiplier:1.0f
                                                      constant:0.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel
                                                     attribute:NSLayoutAttributeWidth
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeWidth
                                                    multiplier:1.0f
                                                      constant:0.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel
                                                     attribute:NSLayoutAttributeHeight
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:nil
                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                    multiplier:1.0f
                                                      constant:30.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_messageLabel
                                                     attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeBottom
                                                    multiplier:1.0f
                                                      constant:-40.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_messageLabel
                                                     attribute:NSLayoutAttributeCenterX
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeCenterX
                                                    multiplier:1.0f
                                                      constant:0.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_messageLabel
                                                     attribute:NSLayoutAttributeWidth
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeWidth
                                                    multiplier:1.0f
                                                      constant:0.0f]];

    [self addConstraint:[NSLayoutConstraint constraintWithItem:_messageLabel
                                                     attribute:NSLayoutAttributeHeight
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:nil
                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                    multiplier:1.0f
                                                      constant:50.0f]];

    [super updateConstraints];
}

@end

Parent View Controller:

#import "PCCLeaveRatingViewController.h"
#import "PCCGenericRating.h"
#import "PCCSliderRatingView.h"

@interface PCCLeaveRatingViewController ()

@end

@implementation PCCLeaveRatingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.dataSource = @[ [[PCCGenericRating alloc] initWithTitle:@"Easiness"
                                                      andMessage:@"WHAT A JOKERRRR"
                                                    andVariatons:@[ @"very easy", @"easy", @"moderate", @"hard", @"very hard"]],
                         ];

    [self initView];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)initView {
    [self setupConstraints];
    [self addViewController];

}

- (void)setupConstraints {
    CGRect windowFrame = [[UIApplication sharedApplication].delegate window].frame;
    CGFloat windowWidth = windowFrame.size.width * self.dataSource.count;

    [self.containerView addConstraint:[NSLayoutConstraint constraintWithItem:self.containerView
                                                                   attribute:NSLayoutAttributeWidth
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:nil
                                                                   attribute:NSLayoutAttributeNotAnAttribute
                                                                  multiplier:1.0f
                                                                    constant:windowWidth]];

    [self.containerView addConstraint:[NSLayoutConstraint constraintWithItem:self.containerView
                                                                   attribute:NSLayoutAttributeHeight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:nil
                                                                   attribute:NSLayoutAttributeNotAnAttribute
                                                                  multiplier:1.0f
                                                                    constant:windowFrame.size.height]];
}

- (void)addViewController {
    PCCGenericRating *rating = self.dataSource[0];
    PCCGenericRatingView *view = [PCCGenericRatingView genericRatingViewWithTitle:rating.title andMessage:rating.message];
    [view setBackgroundColor:[UIColor yellowColor]];

    const CGFloat viewWidth = [UIScreen mainScreen].bounds.size.width;
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(view);
    NSDictionary *metrics = @{ @"viewWidth" : @(viewWidth) };

    [_containerView addSubview:view];

    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(==viewWidth)]" options:0 metrics:metrics views:viewsDictionary]];
    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:viewsDictionary]];


}

@end

Upvotes: 0

Views: 464

Answers (1)

Shobhakar Tiwari
Shobhakar Tiwari

Reputation: 7892

print out the view property to trace whether it is pointing the view which you are referring or other [view setBackgroundColor:[UIColor yellowColor]]

Upvotes: 0

Related Questions