【问题标题】:UITextView - addSubview - AutolayoutUITextView - addSubview - 自动布局
【发布时间】:2014-03-25 13:05:59
【问题描述】:
问题:
- 我创建了
UITextView 的子类并添加了子视图 v1。
- 我正在使用 Autolayout,所以我尝试添加约束来定位子视图 v1。
错误:
它会抛出以下错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews.
尝试次数:
- 我尝试在
layoutSubviews 中创建约束,但我得到了同样的错误
目标
问题:
- 有没有更好的方法来实现我的目标?
- 如何解决此错误?
【问题讨论】:
标签:
ios
uitextview
autolayout
【解决方案1】:
感谢@mackworth 提出解决方案的建议
为了完整起见,我正在回答它。
概述:
在UITextView 上添加子视图然后使用自动布局似乎有些麻烦。
解决方案:
因此解决方案是将 HazeView 创建为 UITextView 的父视图的子视图。
步骤:
- 创建
UITextView
- 创建一个 HazeView(UIView 的子类)
- 将
UITextView 和HazeView 作为子视图添加到同一个父视图中
- 将
HazeView 定位在UITextView 的底部
- 确保HazeView的背景颜色为
[UIColor clearColor]
- 在
HazeView 上禁用用户交互
- 最好创建一个
UIView的子类,并把UITextView和HazeView放在里面,这样就可以复用了
创建 HazeView:
self.hazeView.backgroundColor = [UIColor clearColor];
HazeView 是UIView 的子类
- (void)drawRect:(CGRect)rect
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *color1 = [UIColor colorWithRed:1.0 green:1.0
blue:1.0 alpha:0.25];
UIColor *color2 = [UIColor colorWithRed:1.0 green:1.0
blue:1.0 alpha:0.5];
UIColor *color3 = [UIColor colorWithRed:1.0 green:1.0
blue:1.0 alpha:0.75];
NSArray *gradientColors = @[(id) color1.CGColor,
(id) color2.CGColor,
(id) color3.CGColor];
CGFloat gradientLocations[] = {0, 0.50, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) gradientColors, gradientLocations);
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);
}
【解决方案2】:
我建议您使用以下库进行自动布局:
https://github.com/jrturton/UIView-Autolayout
用这个很容易添加约束。
创建UITextView的子类并在-(void)didMoveToSuperview中添加约束
如:
-(void)didMoveToSuperview
{
[self.subview pinToSuperviewEdges:JRTViewPinBottomEdge | JRTViewPinLeftEdge | JRTViewPinRightEdge inset:0];
[self.subview constrainToHeight:10];
}