【问题标题】: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 中创建约束,但我得到了同样的错误

目标

  • 我的主要目标是在文本视图的底部添加淡入淡出效果

问题:

  1. 有没有更好的方法来实现我的目标?
  2. 如何解决此错误?

【问题讨论】:

标签: ios uitextview autolayout


【解决方案1】:

感谢@mackworth 提出解决方案的建议

为了完整起见,我正在回答它。

概述:

UITextView 上添加子视图然后使用自动布局似乎有些麻烦。

解决方案:

因此解决方案是将 HazeView 创建为 UITextView 的父视图的子视图。

步骤:

  1. 创建UITextView
  2. 创建一个 HazeView(UIView 的子类)
  3. UITextViewHazeView 作为子视图添加到同一个父视图中
  4. HazeView 定位在UITextView 的底部
  5. 确保HazeView的背景颜色为[UIColor clearColor]
  6. HazeView 上禁用用户交互
  7. 最好创建一个UIView的子类,并把UITextViewHazeView放在里面,这样就可以复用了

创建 HazeView:

self.hazeView.backgroundColor = [UIColor clearColor];

HazeViewUIView 的子类

- (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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多