UITextview gains an extra line when it should not - iphone

I wonder if there is someone out there that can shed some light as to what is happening in my app. I have created a multiline text box using the UITextView. When the view loads it is a single line textbox and as the user types out their message I increase the size according. Pretty much how the SMS app works.
The problem is it is doing something rather funky when adding new lines. What happens is when you get to end of the line when it is meant to add a new line it seems to add 2 new lines and as soon as you enter another character the 2nd additional line disappears and I am left with just the 1 new additional line.
I have outputted my values to the console when as each letter is added. All the values are correct, even when the 2nd additional line is added, mathematically and code wise the height value of the textview is the same with and without the this 2nd line for 1 character. (The same results happen when using the debugger to inspect the various values)
I have placed my function below for you code boffins to cast your eye over and tell me what I am doing wrong.
-(void) keyPressed: (NSNotification*) notification{
// check if there is text in the text box
if (chatTextView.hasText)
{
chatTextButton.enabled = YES;
CGSize expectedSize = [[[notification object]text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(210,9999) lineBreakMode:UILineBreakModeWordWrap];
NSInteger expectedHeight = expectedSize.height;
if (expectedHeight < 30)
{
[chatTextView scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
}

 if (expectedHeight >= 30 && expectedHeight <= 126)
{
//text view resizing
CGRect frameTextView = chatTextView.frame;
NSInteger frameTextW = frameTextView.size.width;
frameTextView.size.height = expectedHeight + 12;
chatTextView.frame = frameTextView;
//chat view resizing
CGRect frameChat = chatTextBoxView.frame;
NSInteger frameChatH = frameChat.size.height;
NSInteger frameChatY = frameChat.origin.y;
frameChat.origin.y = 202 - (expectedHeight + 27);
frameChat.size.height = (expectedHeight + 12);
chatTextBoxView.frame = frameChat;
//main view resizing
CGRect frameMain = self.view.frame;
NSInteger frameMainH = frameMain.size.height;
frameMain.size.height = 247 - (expectedHeight + 27);
self.view.frame = frameMain;
NSLog(#"==== EXPECTED HEIGHT %d =====",expectedHeight);
NSLog(#"==== CHAT TEXT WIDTH %d =====",frameTextW);
NSLog(#"==== CHAT VIEW HEIGHT %d =====",frameChatH);
NSLog(#"==== CHAT VIEW LOCATY %d =====",frameChatY);
NSLog(#"==== MAIN VIEW HEIGHT %d =====",frameMainH);
NSLog(#"==============================");
[chatTextView scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
}
if (expectedHeight > 126)
{
chatTextView.scrollEnabled = YES;
}
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];
[UIView commitAnimations];
[self scrollThread];
}
If anyone can help please please, I don' have much hair left. Many thanks in advance.

Related

animation similar to opening app in ios7

I want to create an animation similar to app opens in iPhone in iOS7. In this animation it just shows that app is opening from which point and closing at same point.
Can anyone please help me?
#property (weak, nonatomic) IBOutlet UIImageView *bg;
#property (weak, nonatomic) IBOutlet UIImageView *cal;
…
bool nowZoomed = NO;
CGRect iconPosition = {16,113,60,60}; // customize icon position
- (CGRect)zoomedRect // just a helper function, to get the new background screen size
{
float screenWidth = UIScreen.mainScreen.bounds.size.width;
float screenHeight = UIScreen.mainScreen.bounds.size.height;
float size = screenWidth / iconPosition.size.width;
float x = screenWidth/2 - (CGRectGetMidX(iconPosition) * size);
float y = screenHeight/2 - (CGRectGetMidY(iconPosition) * size);
return CGRectMake(x, y, screenWidth * size, screenHeight * size);
}
- (IBAction)test
{
float animationDuration = 0.3f; //default
if (nowZoomed) // zoom OUT
{
[UIView animateWithDuration:animationDuration animations:^{ // animate to original frame
_cal.frame = iconPosition;
_bg.frame = UIScreen.mainScreen.bounds;
} completion:^(BOOL finished) {
[UIView animateWithDuration:animationDuration/2.0f animations:^{ // then fade out
_cal.alpha = 0.0f;
} completion:^(BOOL finished) {
_cal.hidden = YES;
}];
}];
}
else // zoom IN
{
_cal.alpha = 0.0f;
_cal.hidden = NO;
[UIView animateWithDuration:animationDuration/2.0f animations:^{ // fade in faster
_cal.alpha = 1.0f;
}];
[UIView animateWithDuration:animationDuration animations:^{ // while expanding view
_cal.frame = UIScreen.mainScreen.bounds;
_bg.frame = [self zoomedRect];
}];
}
nowZoomed = !nowZoomed;
}
you can test it, by creating a sample project like this:
make two screenshots from simulator like I did (homescreen and calendar view) or grab these two: homescreen / calendar
add 2 image views and 1 button into storyboard
make the background image view as big as the whole screen
and the other image view with this dimensions: {16,113,60,60}
create an IBOutlet for both (the very first two lines of code)
set the button action target to -(void)test
the storyboard picture (left) and animation transition (right)
I personally prefer to use CGAffineTransformMakeScale() and setting -[CALayer affineTransform] in this case.
affineTransform is super easy to use and comes with a few nice, implicit benefits from Core Animation. Examples being that does things like handling of changing the frame's origin for you implicitly and making it really easy to reset back to the initial size if needed -- you never lost it in the first place!
[UIView animateWithDuration:0.3 animations:^{
view.layer.affineTransform = CGAffineTransformMakeScale(10.0, 10.0); // To make a view larger:
otherView.layer.affineTransform = CGAffineTransformMakeScale(0.0, 0.0); // to make a view smaller
}];
and
// To reset views back to their initial size after changing their sizes:
[UIView animateWithDuration:0.3 animations:^{
view.layer.affineTransform = CGAffineTransformIdentity;
otherView.layer.affineTransform = CGAffineTransformIdentity;
}];
As far as I know, that animation is made using screenshots. It updates the frame of the view and simultaneously makes a smooth transition from the app logo to the screenshot from the app. I have imitated the opening of the iPod (music) application from the bottom right corner of the device to the screen size:
UIView * v = [[UIView alloc]init];
CGSize size = self.view.bounds.size;
CGRect frameInitial = CGRectMake(size.width - 30, size.height - 30, 20, 20);
CGRect frameFinal = CGRectMake(0,0, size.width, size.height);
[v setFrame:frameInitial];
Then use the lines below when you want to animate the frame size:
[UIView animateWithDuration:0.3f
delay:0.0f
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[v setFrame:frameFinal];
} completion:nil];
Edit: Did not realize that the zooming also included the background. The code below is not tested (I am not at work) so expect some defects and typos.
Imagine you have two layers on the view controller's view. Directly on the vc there is the app you want to be opened, lets call it finalView. And on the top layer there is the window with all apps, which will zoom and fade into your app, which is a view behind it. Lets call it firstView.
Initial cond: firstView has a frame of 320 x 480 (It is a window with all the app icons). It has an alpha of 1. finalView has the same frame and alpha, but it is behind firstView.
Final cond: finalView will still have the same frame and alpha. But firstView will zoom into bottom right corner (will have a huge frame) and fade out (alpha -> 0).
//Initial cond: (Or better yet use IB)
CGRect frameInitial = CGRectMake(0,0, self.view.size.width, self.view.size;
CGRect frameFinal = CGRectMake(self.view.size.width * -4 ,self.view.size.height * -5, self.view.size.width * -5,self.view.size.width * -6);
[v setFrame:frameInitial];
Then use the lines below when you want to animate the frame size:
[UIView animateWithDuration:0.3f
delay:0.0f
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[v setFrame:frameFinal];
} completion:nil];
I have small repo that uses a UICollectionViewFloatLayout to create the zoom effect, https://github.com/MichaelQuan/ios7ZoomEffect. It is still a work in progress but the basic idea is there
The layout code is:
#interface ExpandingCollectionViewLayout ()
#property (nonatomic, assign) CGRect selectedCellFrame;
#property (nonatomic, strong) NSIndexPath *selectedIndexPath;
#end
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *layoutAttributes = [super layoutAttributesForElementsInRect:rect];
[layoutAttributes enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *obj, NSUInteger idx, BOOL *stop) {
[self _transformLayoutAttributes:obj];
}];
return layoutAttributes;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *layoutAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
[self _transformLayoutAttributes:layoutAttributes];
return layoutAttributes;
}
- (void)_transformLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
if (self.selectedIndexPath != nil)
{
if ([layoutAttributes.indexPath isEqual:self.selectedIndexPath]) {
// set the frame to be the bounds of the collectionView to expand to the entire collectionView
layoutAttributes.frame = self.collectionView.bounds;
} else {
//scale = collectionView.size / cell_selected.size
//translate = (scale - 1)(cell_i.center - cell_selected.center) + (collectionView.center - cell_selected.center)
CGRect collectionViewBounds = self.collectionView.bounds;
CGRect selectedFrame = self.selectedCellFrame;
CGRect notSelectedFrame = layoutAttributes.frame;
// Calculate the scale transform based on the ratio between the selected cell's frame and the collection views bound
// Scale on that because we want everything to look scaled by the same amount, and the scale is dependent on how much the selected cell has to expand
CGFloat x_scale = collectionViewBounds.size.width / selectedFrame.size.width;
CGFloat y_scale = collectionViewBounds.size.height / selectedFrame.size.height;
CGAffineTransform scaleTransform = CGAffineTransformMakeScale(x_scale, y_scale);
// Translation based on how much the selected cell has been scaled
// translate based on the (scale - 1) and delta between the centers
CGFloat x_zoomTranslate = (x_scale - 1) * (CGRectGetMidX(notSelectedFrame) - CGRectGetMidX(selectedFrame));
CGFloat y_zoomTranslate = (y_scale - 1) * (CGRectGetMidY(notSelectedFrame) - CGRectGetMidY(selectedFrame));
CGAffineTransform zoomTranslate = CGAffineTransformMakeTranslation(x_zoomTranslate, y_zoomTranslate); //Translation based on how much the cells are scaled
// Translation based on where the selected cells center is
// since we move the center of the selected cell when expanded to full screen, all other cells must move by that amount as well
CGFloat x_offsetTranslate = CGRectGetMidX(collectionViewBounds) - CGRectGetMidX(selectedFrame);
CGFloat y_offsetTranslate = CGRectGetMidY(collectionViewBounds) - CGRectGetMidY(selectedFrame);
CGAffineTransform offsetTranslate = CGAffineTransformMakeTranslation(x_offsetTranslate, y_offsetTranslate);
// multiply translations first
CGAffineTransform transform = CGAffineTransformConcat(zoomTranslate, offsetTranslate);
transform = CGAffineTransformConcat(scaleTransform, transform);
layoutAttributes.transform = transform;
}
}
}
To expand a cell using this layout code, set both the selectedCellFrame and selectedIndexPath to the cell you want expanded and call performBatchUpdates:completion: on the collection view. To collapse set selectedCellFrame = CGRectNull and selectedIndexPath = nil and call performBatchUpdates:completion:

iOS: Scaling UITextView with pinching?

I'm interested in creating UITextView that is expanding dynamically while typing the text, and scaling as the user pinches the screen(Similar behaviour can be found in TinyPost).
When you just type (without pinching) the textView expands fine. When you just pinch (without typing) is works fine, but when you pinch and then type, the text inside gets cut.
Here is my code:
UIPinchGestureRecognizer *pinchGestRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(scaleTextView:)];
pinchGestRecognizer.delegate = self;
[bgFrameImageView addGestureRecognizer:pinchGestRecognizer];
- (void)scaleTextView:(UIPinchGestureRecognizer *)pinchGestRecognizer{
createTextView.transform = CGAffineTransformScale(createTextView.transform, pinchGestRecognizer.scale, pinchGestRecognizer.scale);
pinchGestRecognizer.scale = 1;
}
- (void)textViewDidChange:(UITextView *)textView{
CGSize textSize = textView.contentSize;
textView.frame = CGRectMake(CGRectGetMinX(textView.frame), CGRectGetMinY(textView.frame), textSize.width, textSize.height); //update the size of the textView
}
What do you think?
Try:
- (void)scaleTextView:(UIPinchGestureRecognizer *)pinchGestRecognizer{
CGFloat scale = pinchGestRecognizer.scale;
createTextView.font = [UIFont fontWithName:createTextView.font.fontName size:createTextView.font.pointSize*scale];
[self textViewDidChange:createTextView];
}
It basically scales the font size and then recalculates the content size using your code in textViewDidChange.
To elaborate on #Cocoanetics answer above. I implemented the gesture handling idea for attributed strings on iOS 7 but it is prohibitively slow when you have too many font changes in your string. There is also a ridiculous buffering bug in iOS 7 where Change notifications keep firing long after you've stopped pinching - reminds me of the stupid keyboard buffer in early versions of PC-DOS. Anyway, I have put the code below that got this working for me - although it has only resulted in informing me that this is a waste of time and that I need to give my users some other way of scaling their fonts.
- (void)scaleTextView:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
CGFloat scale = 0;
NSMutableAttributedString *string;
switch (pinchGestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
self.old_scale = 1.0;
self.last_time = [NSDate date];
break;
case UIGestureRecognizerStateChanged:
scale = pinchGestureRecognizer.scale - self.old_scale;
if( [self.last_time timeIntervalSinceNow] < -0.2 ) { // updating 5 times a second is best I can do - faster than this and we get buffered changes going on for ages!
self.last_time = [NSDate date];
string = [self getScaledStringFrom:[self.textview.attributedText mutableCopy] withScale:1.0 + scale];
if( string ) {
self.textview.attributedText = string;
self.old_scale = pinchGestureRecognizer.scale;
}
}
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
case UIGestureRecognizerStateFailed:
break;
default:
break;
}
}
- (NSMutableAttributedString*) getScaledStringFrom:(NSMutableAttributedString*)string withScale:(CGFloat)scale
{
[string beginEditing];
[string enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, string.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
UIFont *oldFont = (UIFont *)value;
UIFont *newFont = [oldFont fontWithSize:oldFont.pointSize * scale];
[string removeAttribute:NSFontAttributeName range:range];
[string addAttribute:NSFontAttributeName value:newFont range:range];
}
}];
[string endEditing];
return string;
}
First of all add UIPinchGestureRecognizer in viewDidLoad method:
UIPinchGestureRecognizer *pinchOnTextfield = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handleTextFieldFontOnAddMusicVc:)];
[self.myTextField addGestureRecognizer:pinchOnTextfield];
then put this method in your viewController to scale textField font:
- (void)handleTextFieldFontOnAddMusicVc:(UIPinchGestureRecognizer *)pinchGestRecognizer {
if (pinchGestRecognizer.state == UIGestureRecognizerStateEnded || pinchGestRecognizer.state == UIGestureRecognizerStateChanged) {
CGFloat currentFontSize = self.myTextField.font.pointSize;
CGFloat newScale = currentFontSize * pinchGestRecognizer.scale;
if (newScale < 20.0) {
newScale = 20.0;
}
if (newScale > 60.0) {
newScale = 60.0;
}
self.myTextField.font = [UIFont fontWithName:self.myTextField.font.fontName size:newScale];
pinchGestRecognizer.scale = 1;
}
}
UITextView is a subclass of UIScrollView and as such you need to do what you do with any scroll view to enable zooming:
set the minimum and maximum zoom scale properties
set the viewForZooming via the scrollview delegate method
... that zooms the entire text view.
If you only want to zoom the text then you have to perform these steps via a pinch gesture recognizer:
retrieve the current attributed string
walk through the font ranges and replace the font attribute with a scaled one
replace the text in the text view with your modified version
probably you also need to set the text selection after setting the text
Not the best but easy solution would be:
I do not know exactly your use case, but I think it does not make sense in many cases to support in a app pinch zoom while typing text. I would just set a flag, which prevents pinch zoom while user is typing text.
If you mean by text typing, editing the text view you can end the editing at the beginning of the pinch gesture and start editing after pinch gesture did end.

UISCrollview+enable left side scrolling

I have a UIScrollView. I want to implement an infinite left side-scrolling effect. How can this be possible?
- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = scrollView.frame.size.width/7;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
Lbl_Rate.text=[NSString stringWithFormat:#" pagenumber==>%d",page ];
int p=page%10;
if(p==0){
page=1;
SCrl_Wheel.contentOffset = CGPointMake(0, 0);
}
}
I had trid to set contentoffset by SCrl_Wheel.contentOffset = CGPointMake(0, 0);
But it is not actually setting contentoffset.x=0;
And this is making :-[SCrl_Wheel setContentOffset:CGPointMake(0,0) animated:YES]; my loop as infinite loop.
Add this setContentSize: to your code.
[SCrl_Wheel setContentSize:CGSizeMake(-100000,50)];
Now it would scroll like the way you want to and why hav u added your y = 0 ?? then the height of the UIScrollView would be 0....
EDIT:
[SCrl_Wheel setContentOffset:CGPointMake(1000, 0.0)];
Add this code ull b getting both sides scrolling ur way :) I tested it ...
To add Left Side scrolling effect, you can create a scrollview with very large width and then set its initial contentOffset to midpoint of contentwidth of scrollview :
scrollView.contentSize = CGSizeMake(100000, 60);
scrollView.contentOffset = CGPointMake(scrollView.contentSize.width/2, 0);
This is the code I used for scrolling left:
HorizontalScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,50,yourView.frame.size.width,tbv.frame.size.height)];
[HorizontalScroll setContentSize:CGSizeMake(930,340)];
[HorizontalScroll setBackgroundColor:[UIColor redColor]]; // color is set just to know where the scroll view is , remove this line afterwards.
[self.view addSubview:HorizontalScroll];
[HorizontalScroll addSubview:yourView];

UIScrollview content display problem

i have a scollview and i want to display suppose 10 images. frame width is 320 for iphone and 768 for ipad.
something like this image
middle image will be our current selection(mountain image according to this snapshot).
Now i want to scroll left or right to check all the images.
If waterfall is at position 1 mountain at position 2 and hut at position 3, when i scroll right i want to show mountain at position 1 hut at position2 and a new image at position 3.
PLZ tell me how to do this
You have to adjust and set the contentOffset of the scrollView based on the size of the image. You must also set the necessary contentSize for the scrollView which will enable the scrolling.
hey use content offset.
and use this code u get what you want.
this is a scrollview for two image at a time seen on iPhone and when a image scroll at middle of iPhone the label set midlle image label.. as you set width 320 change to 320
-(void)scrollViewDidScroll:(UIScrollView *)inscrollView{
p = scrollView.contentOffset;
NSLog(#"x = %f, y = %f", p.x, p.y);
[self loadDescLbl];
}
-(void)loadDescLbl
{
int point;
point = p.x+160;
int i;
i = point / 160;
i = i-1;
if(i > fetArray.count-1){
i = fetArray.count -1;
}
if(i == -1)
{
i = 0;
}
imageView[i].highlighted = YES;
if([yourArray objectAtIndex:i] isEqualToString:#""]){
priceLbl.text = #"";
}
else {
priceLbl.text = [NSString stringWithFormat:#"%#", [yourArray objectAtIndex:i]];
}
[scroll addSubview:priceLbl];
// }
}
just set point = p.x
and i = point;
if you get problem then tell me...
f all of your images are of the same size you could add 2 buttons (left right) ... and when you tap one of them change the content offset's frame with the width of one picture ...
if you don't want buttons you can obtain the same effect with UISwipeGestureRecognizer
-(IBAction)changeVisibleRect:(UIButton *)btn {
[UIView beginAnimation:#"animation name" context:nil];
[UIView setAnimationDuration:0.3]; //or how much you want in seconds
[scrollview.contentOffset setFrame:CGRectMake(pictureSize * i, 0, pictureSizeWidth, pictureSizeHeight)]; //i = the number of the picture
[UIView commitAnimations];
}
CGRectMake(pictureSize * i, 0, pictureSizeWidth, pictureSizeHeight)] ... instead of pictureSize * i ... you could asign you left or right buttons tags and ... make a
if(btn.tag == 1) {
[UIView beginAnimation:#"animation name" context:nil];
[UIView setAnimationDuration:0.3]; //or how much you want in seconds
[scrollview.contentOffset setFrame:CGRectMake(scrollView.contentOffset.frame.origin.x - pictureSizeWidth, 0, pictureSizeWidth, pictureSizeHeight)]; //i = the number of the picture
[UIView commitAnimations];
}
assuming your left button has set tag = 1;
for the SwipeGesture it would be the same animation code / idea

Drawing ruled lines on a UITextView for IPhone

I would like to create a view like the notes app on iPhone and therefor need the view to have ruled lines as per the notes app, I have done this in windows where you need to get the font metrics and then draw the lines onto the device context, has anyone done this in the UITextView if so some help would be appriciated
Subclass UITextView. Override -drawRect:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);
CGContextSetLineWidth(context, self.lineWidth);
CGFloat strokeOffset = (self.lineWidth / 2);
CGFloat rowHeight = self.font.lineHeight;
if (rowHeight > 0) {
CGRect rowRect = CGRectMake(self.contentOffset.x, - self.bounds.size.height, self.contentSize.width, rowHeight);
while (rowRect.origin.y < (self.bounds.size.height + self.contentSize.height)) {
CGContextMoveToPoint(context, rowRect.origin.x + strokeOffset, rowRect.origin.y + strokeOffset);
CGContextAddLineToPoint(context, rowRect.origin.x + rowRect.size.width + strokeOffset, rowRect.origin.y + strokeOffset);
CGContextDrawPath(context, kCGPathStroke);
rowRect.origin.y += rowHeight;
}
}
}
When you init the text view, be sure to set the contentMode to UIViewContentModeRedraw. Otherwise the lines won't scroll with the text.
self.contentMode = UIViewContentModeRedraw;
This isn't perfect. Ideally you should just draw into the rect that's passed. But I was lazy and this worked for my needs.
I think this works OK but I feel it has been hacked and I do not fully undestand the mechanism of the UITextView class;
first you must add the following to your delegate to force a redraw on scrolling
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// NSLog(#"scrollViewDidScroll The scroll offset is ---%f",scrollView.contentOffset.y);
[noteText setNeedsDisplay];
}
then implement drawRect in the subclass as so
- (void)drawRect:(CGRect)rect {
// Drawing code
// Get the graphics context
CGContextRef ctx = UIGraphicsGetCurrentContext();
[super drawRect:rect];
// Get the height of a single text line
NSString *alpha = #"ABCD";
CGSize textSize = [alpha sizeWithFont:self.font constrainedToSize:self.contentSize lineBreakMode:UILineBreakModeWordWrap];
NSUInteger height = textSize.height;
// Get the height of the view or contents of the view whichever is bigger
textSize = [self.text sizeWithFont:self.font constrainedToSize:self.contentSize lineBreakMode:UILineBreakModeWordWrap];
NSUInteger contentHeight = (rect.size.height > textSize.height) ? (NSUInteger)rect.size.height : textSize.height;
NSUInteger offset = 6 + height; // MAGIC Number 6 to offset from 0 to get first line OK ???
contentHeight += offset;
// Draw ruled lines
CGContextSetRGBStrokeColor(ctx, .8, .8, .8, 1);
for(int i=offset;i < contentHeight;i+=height) {
CGPoint lpoints[2] = { CGPointMake(0, i), CGPointMake(rect.size.width, i) };
CGContextStrokeLineSegments(ctx, lpoints, 2);
}
}
Still worry about this Magic Number 6
Bob
You can try setting the backgroundColor of you textView using an image with ruled lines
textView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"RuledLinesPage.png"]];
Color with pattern image creates a tiled image if the area to be filled with the color is larger than the image. So you will have to make sure that the image size is correct size/tileable (I don't think 'tileable' is a real word but i hope you get what i mean). Also you will have to create the image with ruled lines to best match you textView's font.
Good Luck.
#lukya,
Your solution is bit messy as when we scroll the UITextView the text only scrolls leaving the lines (coming from the image) in its place.
A better solution would be to add subview to your text view where you have drawn the lines. You need to add an observer to the text view in order to track its change in content size as the text increase/decrease.