Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView - addSubview - Autolayout

Problem:

  • I have created a subclass of UITextView and added a subview v1.
  • I am using Autolayout, so I tried to add constraints for positioning the subview v1.

Error:

It throws the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews.

Attempts Made:

  • I have tried creating the constraints inside layoutSubviews and yet i get the same error

Objective

  • My main objective is to add a fading effect at the bottom of the text view

Question:

  1. Is there a better way to attain my objective ?
  2. How do I resolve this error ?
like image 947
user1046037 Avatar asked Nov 01 '22 02:11

user1046037


1 Answers

Thanks to @mackworth for the suggestion which led to the solution

For completeness I am answering it.

Overview:

There seems to be some trouble adding subview on UITextView and then using Autolayout.

Solution:

So the solution is to create the HazeView as a subview to the parent view of UITextView.

Steps:

  1. Create a UITextView
  2. Create a HazeView (subclass from UIView)
  3. Add both UITextView and HazeView as subview to the same parent view
  4. Position HazeView at the bottom of the UITextView
  5. Ensure that the background colour of HazeView is [UIColor clearColor]
  6. Disable user interaction on HazeView
  7. It is best to create a subclass of UIView and put the UITextView and HazeView inside that so that it can be reusable

Creating HazeView:

self.hazeView.backgroundColor = [UIColor clearColor];

HazeView is a subclass of 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);
}
like image 155
user1046037 Avatar answered Nov 08 '22 08:11

user1046037