Skip to main content

Create custom UITextFields and UITextViews with underline


Download


In a recent iOS project I needed to create custom UITextView and UITextField. The look and feel had to be same as the Notes app, i.e. the text view and text field both should have horizontal lines as are present in a note.


How to create a custom UIView
To create a custom UIView we need to inherit from UIView class. We then need to override drawRect method. Override only if you need to change the way view is drawn as this is a performance intensive operation.

Custom UITextField
In order to create custom UITextField I inherited my class from UITextField. I need to draw a bottom border for this I need override drawRect method.


    //Get the current drawing context
    CGContextRef context = UIGraphicsGetCurrentContext();
    //Set the line color and width
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 0.5f);
    //Start a new Path
    CGContextBeginPath(context);
    
    // offset lines up - we are adding offset to font.leading so that line is drawn right below the characters and still characters are visible.
    CGContextMoveToPoint(context, self.bounds.origin.x, self.font.lineHeight + 6.0f);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.font.lineHeight + 6.0f);
    
    //Close our Path and Stroke (draw) it
    CGContextClosePath(context);
    CGContextStrokePath(context);

We need to grab a graphic context us we are going to draw a custom UI. Then we need to set color to the context and the line width. Line width, because we need a line under our control. Now, the tricky part:

We need to set the start and end coordinates for line. For this we need the line height so that we can set the Y coordinate correctly. Fortunately iOS provides a simple to get this. self.font.lineHeight. Using this we are asking the view to tell us about the lineHeight based on the font.

Thats it.

Custom UITextView
Approach remains same here. But, we need multiple lines and we need lines to appear even if we scroll.


- (void)drawRect:(CGRect)rect {
    
    //Get the current drawing context
    CGContextRef context = UIGraphicsGetCurrentContext();
    //Set the line color and width
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextSetLineWidth(context, 1.0f);
    //Start a new Path
    CGContextBeginPath(context);
    
    //Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
    NSUInteger numberOfLines = (self.contentSize.height + self.bounds.size.height) / self.font.leading;
    
    //Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.)
    CGFloat baselineOffset = 6.0f;
    
    //iterate over numberOfLines and draw each line
    for (int x = 1; x < numberOfLines; x++) {
        //0.5f offset lines up line with pixel boundary
        CGContextMoveToPoint(context, self.bounds.origin.x + 10, self.font.leading*x + 0.5f + baselineOffset);
        CGContextAddLineToPoint(context, self.bounds.size.width - 10, self.font.leading*x + 0.5f + baselineOffset);
    }
    
    //Close our Path and Stroke (draw) it
    CGContextClosePath(context);
    CGContextStrokePath(context);
}

Here we need to calculate the number of lines before drawing. So, why are we adding contentsize.height and bounds.height. If we will use just the contentsize.height then:

1. We do not have any content initially and thus we will not have any line.
2. There won't be any lines at the bottom (after the content)

Thus, for a consistent and better view we will add textview's bounds.


Comments

  1. Amazing blog ever come across on the internet. In case you need online assignment help, then sourceessay.com will be the best place to learn the amazing writing techniques from assignment writers. Research proposal Perth

    ReplyDelete

Post a Comment

Popular posts from this blog

Create a background / taskbar application in c# .NET

Recently, I was working on integration of two windows applications. First application will launch the second application on login and then they both will communicate using pre-defined set of instructions. There were some complications (I am not going into them) and thus we decided to have a third application which actually will act as mediator. First application will launch the mediator (third application) and it will launch the second application. For this purpose we needed to create a task bar application (which will run in background). How To ·          Create a new windows project and delete the default form (Form1). ·          In Program.cs create a new class and inherit it from Form. ·          Please refer the code below. ·          Now change the Main method. In Application.Run change the startup objec...

Check SQL Server Job status (State) using sp_help_job and xp_sqlagent_enum_jobs

This article is about checking the status of a SQL job. In our work place we have lot of SQL jobs. These jobs will run whole day and are business critical. They will load the data and generate extracts which will be used by business people. Thus, it becomes quite essential to support the system efficiently so that the job finishes in time and as desired. Also, while designing a new system sometimes we need to check the dependency of one job over another. In such scenario we need to check whether a particular job has finished or not. All this can be achieved in SQL Server by using the procedures:- sp_help_job xp_sqlagent_enum_jobs Note: xp_sqlagent_enum_jobs is an undocumented proc inside of sp_help_job and is used extensively to get SQL agent job information. sp_help_job: This procedure gives some insight into the status, and information, about a job. This stored procedure provides information such as last start time, job status etc. Syntax sp_help_job { [ @job_id= ] jo...

Java 8 JMX Default Metrics

This is more of a note. Here you can find default types and attributes for JMX on top of Java 8. Code: I will clean and explain it later :( private static void WriteAttributes(final MBeanServer mBeanServer, final ObjectName http) throws InstanceNotFoundException, IntrospectionException, ReflectionException { MBeanInfo info = mBeanServer.getMBeanInfo(http); MBeanAttributeInfo[] attrInfo = info.getAttributes(); System.out.println("Attributes for object: " + http +":\n"); for (MBeanAttributeInfo attr : attrInfo) { System.out.println(" " + attr.getName() + "\n"); } } Attributes for object: java.lang:type=MemoryPool,name=Metaspace:   Name   Type   Valid   Usage   PeakUsage   MemoryManagerNames   UsageThreshold   UsageThresholdExceeded   UsageThresholdCount   UsageThresholdSupported   CollectionUsageThreshold   Collectio...