Building a titleView programmatically with constraints (or generally constructing a view with constraints)

后端 未结 6 1798
长情又很酷
长情又很酷 2021-02-03 20:44

I\'m trying to build a titleView with constraints that looks like this:

\"titleView\"

I know how I would do

6条回答
  •  遥遥无期
    2021-02-03 21:24

    Here is my implementation of ImageAndTextView

    @interface ImageAndTextView()
    @property (nonatomic, strong) UIImageView *imageView;
    @property (nonatomic, strong) UITextField *textField;
    @end
    
    @implementation ImageAndTextView
    
    - (instancetype)init
    {
        self = [super init];
        if (self)
        {
            [self initializeView];
        }
    
        return self;
    }
    
    - (void)initializeView
    {
        self.translatesAutoresizingMaskIntoConstraints = YES;
        self.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    
        self.imageView = [[UIImageView alloc] init];
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        self.textField = [[UITextField alloc] init];
        [self addSubview:self.imageView];
        [self addSubview:self.textField];
    
        self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
        self.textField.translatesAutoresizingMaskIntoConstraints = NO;
        //Center the text field
        [NSLayoutConstraint activateConstraints:@[
            [self.textField.centerXAnchor constraintEqualToAnchor:self.centerXAnchor],
            [self.textField.centerYAnchor constraintEqualToAnchor:self.centerYAnchor]
        ]];
    
        //Put image view on left of text field
        [NSLayoutConstraint activateConstraints:@[
            [self.imageView.rightAnchor constraintEqualToAnchor:self.textField.leftAnchor],
            [self.imageView.lastBaselineAnchor constraintEqualToAnchor:self.textField.lastBaselineAnchor],
            [self.imageView.heightAnchor constraintEqualToConstant:16]
        ]];
    }
    
    - (CGSize)intrinsicContentSize
    {
        return CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
    }
    @end
    

提交回复
热议问题