Using NSLayoutConstraint in a subzone in combination with an affine transform

I need to have vertical sliders. To do this, I have a class UIViewthat contains UISlider, and inside initWithFrame:, I rotate the slider with the affine transform 90 degrees.

Now I am adding Autolayout support.

I want to allow the creation of a slider with different lengths so that it can be used in the dynamic sense of Autolayout. This is the code I'm trying to make the rotated slider match the borders UIViewlocated ininitWithFrame:

self = [super initWithFrame:frame];
if(self) {
    self.slider = [[UISlider alloc] init];
    [self addSubview:self.slider];
    self.slider.value = 0;

    self.slider.transform = CGAffineTransformMakeRotation(M_PI * 1.5);
    [self.slider setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.slider attribute: NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.slider attribute: NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.slider attribute: NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0f constant:0.0f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.slider attribute: NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f]];

    self.backgroundColor = [UIColor colorWithWhite:.8 alpha:1.0];
    self.layer.borderWidth = 1;
    self.slider.backgroundColor = [UIColor colorWithRed:.21 green:.95 blue:1 alpha:1];
    self.slider.layer.borderWidth = 1;

    return self;
}

. . 300 300, - 50 300, 300 50. UIView , UISliders .

Vertical slider instances

300 300 , , . , , .

, .

, , , , , .

, , .

, ?

+4
1

, . UIView . . . initWithFrame: IB == TwistedSlider. ...

@interface TwistedSlider ()
@property(weak,nonatomic) UISlider *slider;
@end

@implementation TwistedSlider

- (UISlider *)slider {
    if (!_slider) {
        UISlider *slider = [[UISlider alloc] init];
        [self addSubview:slider];
        _slider = slider;
    }
    return _slider;
}

// this works for any size of this view.  the slider will always be as tall as this view is wide
- (void)layoutSubviews {
    [super layoutSubviews];
    // size it to be as wide as this view height, center it in this view
    self.slider.bounds = CGRectMake(0, 0, self.bounds.size.height, self.slider.bounds.size.height);
    self.slider.center = [self convertPoint:self.center fromView:self.superview];
    // rotate it
    self.slider.transform = CGAffineTransformMakeRotation(M_PI_2);
}

// that it!
@end
+4

Source: https://habr.com/ru/post/1620398/


All Articles