在子视图上使用NSLayoutConstraint与仿射变换相结合

我需要有垂直滑块。 为此,我有一个包含UISliderUIView类,并且在initWithFrame:我将滑块以仿射变换旋转90度。

我现在添加Autolayout支持。

我希望允许滑块以不同的长度进行实例化,以便能够以dynamic的Autolayout方式使用。 这是我想要获得旋转的滑块符合位于initWithFrame:中的UIView的边界的代码initWithFrame:

 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的背景UISliders成蓝色。

垂直滑块实例

300到300之间的问题是,我认为我不能让这个框架如此之大。 还会有其他的意见,我担心那个会阻碍。

左边的问题是滑块太小。

中间那个问题在于,由于滑块已经旋转出视图的框架,所以不可能抓住拇指并移动它。

我也试着约束滑块的顶部到视图的右侧,滑块的右侧到视图的底部,但是这会产生错误和不可预知的结果。

我需要做些什么来改变这些限制条件?

比看起来更简单。 UIView父级都设置为符合布局约束。 它可以更简单地pipe理其滑块子视图这里是整个class级。 这可以使用initWithFrame:代码创build,或者将视图拖放到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's 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's it! @end