iPhone: UITextView not expanding while editing - ios

I am using UITextView on a scroll view ...and I want it to auto expand when I write something in it ...... but I am unable to do it ...
textViewBusiness = [[UITextView alloc] initWithFrame:CGRectMake(25,332,268,60)];
textViewBusiness.text=strMyBusiness;
textViewBusiness.editable=NO;
textViewBusiness.font = [UIFont fontWithName:#"Arial" size: 17.0];
textViewBusiness.layer.borderWidth = 2.0f;
textViewBusiness.layer.borderColor = [[UIColor grayColor] CGColor];
textViewBusiness.backgroundColor = [UIColor clearColor];
[textViewBusiness setTextColor:[UIColor blackColor]];
[self.scrollView addSubview: textViewBusiness];
CGRect frame = textViewBusiness.frame;
frame.size.height = textViewBusiness.contentSize.height;
textViewBusiness.frame = frame;
This code is not working for me ...
Thanks

Make sure the text field's delegate is set...
someTextField.delegate = self;
Then adjust the size of the textView in the appropriate text field delegate method.
- (void)textViewDidChange:(UITextView *)textView;
- (void) textViewDidEndEditing:(UITextView *)textView;
The code you've added above is correct. Just make sure it's in the correct place.
- (void)textViewDidChange:(UITextView *)textView
{
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame = frame;
}
Dynamic expand UITextView

Your code won't work.
You need to divide your code into 2 fragments, then place them into proper places, then your code should work.
Fragment 1 (in my test, I place this fragment in viewDidLoad):
textViewBusiness = [[UITextView alloc] initWithFrame:CGRectMake(25,332,268,60)];
textViewBusiness.text=strMyBusiness;
textViewBusiness.editable=NO;
textViewBusiness.font = [UIFont fontWithName:#"Arial" size: 17.0];
textViewBusiness.layer.borderWidth = 2.0f;
textViewBusiness.layer.borderColor = [[UIColor grayColor] CGColor];
textViewBusiness.backgroundColor = [UIColor clearColor];
[textViewBusiness setTextColor:[UIColor blackColor]];
[self.scrollView addSubview: textViewBusiness];
Ensure that the above fragment run, and your text view is displayed in the screen, then run the second fragment. If your text view is not displayed in the screen, then the contentView is not initialized, and the height is undefined.
Fragment 2 (in my test, I place this fragment in viewDidAppear):
CGRect frame = textViewBusiness.frame;
frame.size.height = textViewBusiness.contentSize.height;
textViewBusiness.frame = frame;
Good luck!

HPGrowingTextView is a UITextView which grows/shrinks with the text and starts scrolling when the content reaches a certain number of lines. Similar to the one Apple uses in the SMS-app. See the link for a small (outdated) screencast.

Related

UILabel NSTextAlignmentRight not working?

I have problem with text right alignment . Actually in my DetailedViewController there is UILabel Called "lblnNewsTitle", For this Lable i am trying to set NSTextAlignmentRight but it doesn't work for me . can any one help me to solve this issue ?
Screenshot 1:
Screenshot 2 :
My Storyboard screenshot 3 :
Here is My Code :
- (void)viewDidLoad
{
[DetailTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[super viewDidLoad];
[self.lblDescription setNumberOfLines:0];
[scrollView setScrollEnabled:YES];
[scrollView setContentSize:CGSizeMake(320, 765)];
self.txtViwNews.text=self.strDescription;
self.lblnNewsTitle.text=self.strTitle;
self.lblnNewsTitle.font=[UIFont fontWithName:#"GEEast-ExtraBold" size:14];
self.txtViwNews.font=[UIFont fontWithName:#"GE SS Unique" size:12];
self.lblnNewsTitle.textAlignment = NSTextAlignmentRight;
self.txtViwNews.textAlignment= NSTextAlignmentRight;
self.lblDateinDetail.text=self.strDate;
self.lblDateinDetail.font=[UIFont fontWithName:#"GEEast-ExtraBold" size:14];
self.lblDateinDetail.textColor=[UIColor blackColor];
[lblnNewsTitle setNumberOfLines:0];
[lblnNewsTitle sizeToFit];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.strDetailImage]];
self.strImage.image = [UIImage imageWithData:data];
// Set border color and width of image
[_strImage.layer setBorderColor:[UIColor blackColor].CGColor];
[_strImage.layer setBorderWidth:1.0];
self.lblDescription.font=[UIFont fontWithName:#"GE SS Unique" size:kLblIntalFont];
self.lblDescription.textAlignment = NSTextAlignmentRight;
[self estimatedHeight:kLblIntalFont];
if (_strImage.image == nil)
{
[_strImage.layer setBorderColor:[UIColor blackColor].CGColor];
[_strImage.layer setBorderWidth:0];
[self.lblnNewsTitle setNumberOfLines:0];
self.lblnNewsTitle.frame = CGRectMake(self.lblnNewsTitle.frame.origin.x, self.lblnNewsTitle.frame.origin.y, self.lblnNewsTitle.frame.size.width, self.lblnNewsTitle.frame.size.height );
self.viwMidImage.frame=CGRectMake(self.viwMidImage.frame.origin.x, self.strImage.frame.origin.y, self.viwMidImage.frame.size.width, self.viwMidImage.frame.size.height);
[self.lblDescription setNumberOfLines:0];
[self.lblDescription sizeToFit];
self.lblDescription.frame = CGRectMake(self.lblDescription.frame.origin.x, self.viwMidImage.frame.origin.y+ self.viwMidImage.frame.size.height,self.lblDescription.frame.size.width,self.lblDescription.frame.size.height );
self.lblDescription.textAlignment = NSTextAlignmentRight;
}
else {
// if (!cell.imgNews ==nil)
self.lblnNewsTitle.frame = CGRectMake(self.lblnNewsTitle.frame.origin.x, self.lblnNewsTitle.frame.origin.y, self.lblnNewsTitle.frame.size.width, self.lblnNewsTitle.frame.size.height );
[self.lblDescription setNumberOfLines:0];
[self.lblDescription sizeToFit];
}
}
add NSTextAlignmentRight in directly in your Attribute Inspector at the same time remove [lblnNewsTitle sizeToFit]; and check
try this
From the Documentation:
- sizeToFit
Resizes and moves the receiver’s content view so it just encloses its
subviews.
You should invoke this method after:
Adding a subview (to the content view)
Altering the size or location of such a subview
Setting the margins around the content view
So, if you do sizeTofit under any alignment, the text will aligned to the left only. To fix this:
You can save the original label's width in a variable and set it after sizeToFit, or give it a fixed width to counter these problems:
If you still wish to use sizeToFit,Do something like this:
myLabel.textAlignment = NSTextAlignmentRight;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
CGRect myFrame = myLabel.frame;
// Resize the frame's width to your requirement)
// width could also be myOriginalLabelFrame.size.width
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, myWidth, myFrame.size.height);
myLabel.frame = myFrame;
you can find more useful info here

Center vertically in UILabel with autoshrink

This is a little different from all the other "How do I center the text in a UILabel" questions here...
I have a UILabel with some text in it, I want to center the text vertically in the UILabel. What's the big deal, right? That's the default. The problem comes because my text is dynamic and I have autoshrink turn on. As the text grows larger, the font size shrinks. You get this behavior.
Notice that the font baseline has not moved, I want it to move so the numbers are centered vertically in the UILabel's frame.
Easy, right? I just remember the frame's original center in viewDidLoad
self.workoutTimeCenter = _workoutTimeLabel.center;
and then I call sizeToFit after I change the the text, right?
[_workoutTimeLabel sizeToFit];
_workoutTimeLabel.center = _workoutTimeCenter;
Well, sizeToFit did, I guess, exactly what it was supposed to do, resize the frame so the text fits without shrinking!
How can I vertically center the text in a UILabel while respecting baselines and autoshrink? (Note, an iOS5 and later solution is fine and I can even deal with an iOS6 and later solution.)
In my experience you can just set the -[UILabel baselineAdjustment] property to UIBaselineAdjustmentAlignCenters to achieve the effect you're describing.
From the docs:
baselineAdjustment
Controls how text baselines are adjusted when text
needs to shrink to fit in the label.
#property(nonatomic) UIBaselineAdjustment baselineAdjustment
Discussion
If the adjustsFontSizeToFitWidth property is set to YES,
this property controls the behavior of the text baselines in
situations where adjustment of the font size is required. The default
value of this property is UIBaselineAdjustmentAlignBaselines. This
property is effective only when the numberOfLines property is set to
1.
and
UIBaselineAdjustmentAlignCenters
Adjust text based relative to the center of its bounding box.
EDIT: adding a full view-controller that demonstrates this:
#interface TSViewController : UIViewController
#end
#implementation TSViewController
- (void) addLabelWithFrame: (CGRect) f baselineAdjustment: (UIBaselineAdjustment) bla
{
UILabel* label = [[UILabel alloc] initWithFrame: f];
label.baselineAdjustment = bla;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont fontWithName: #"Courier" size: 200];
label.text = #"00";
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];
label.userInteractionEnabled = YES;
[self.view addSubview: label];
UIView* centerline = [[UIView alloc] initWithFrame: CGRectMake(f.origin.x, f.origin.y+(f.size.height/2.0), f.size.width, 1)];
centerline.backgroundColor = [UIColor redColor];
[self.view addSubview: centerline];
UITapGestureRecognizer* tgr = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector(onTap:)];
[label addGestureRecognizer: tgr];
}
- (void) viewDidLoad
{
[super viewDidLoad];
[self addLabelWithFrame: CGRectMake(0, 0, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignCenters];
[self addLabelWithFrame: CGRectMake(0, 220, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
}
- (void) onTap: (UITapGestureRecognizer*) tgr
{
UILabel* label = (UILabel*)tgr.view;
NSString* t = [label.text stringByAppendingString: #":00"];
label.text = t;
}
#end
when working in IB, be sure to set align baselines to center
Note: line break CANNOT be word wrap for this to work, so it will NOT work multiline (good to set the line break to Truncate tail)
-(void)fitVerticallyToLabel:(UILabel *)lbl
{
CGFloat fontSize = lbl.frame.size.width / lbl.text.length;
[lbl setFont:[UIFont fontWithName:#"Helvetica-Bold" size:fontSize]];
CGRect rect = lbl.frame;
rect.origin.y += rect.size.height - fontSize;
rect.size.height = fontSize;
[lbl setFrame:rect];
}
How to Use: Call this method after setting the text to your label.
label.text = #"text";
[self fitVerticallyToLabel:label];
Note: I ahev taken UILabel from xib. You can take it programmatically too in that case you will have to set its text alignment NSTextAlignMentCenter
Try to implement this logic:
-(void)adjustLabel1Text1:(NSString *)text1
{
UILabel *lbl_first = [UIFont fontWithName:#"Helvetica" size:12];
text1 = [text1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
float hedingLblHeight = [self calculateHeightOfTextFromWidth:text1 : [UIFont fontWithName:#"Helvetica" size:12] :118 :UILineBreakModeWordWrap];
lbl_first.text=text1;
[lbl_first setFrame:CGRectMake(lbl_first.frame.origin.x, lbl_first.frame.origin.y, 118, hedingLblHeight)];
lbl_first.lineBreakMode = UILineBreakModeWordWrap;
lbl_first.numberOfLines = 0;
[lbl_first sizeToFit];
//////////Adjust the lable or any UIControl below this label accordingly.
float endResultHeight=[self calculateHeightOfTextFromWidth:text2 : [UIFont fontWithName:#"Helvetica" size:15] :299 :UILineBreakModeWordWrap];
if(hedingLblHeight>secondImgTitleHeight)
{
[lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
}
else
{
[lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
}
lbl_endResult.lineBreakMode=UILineBreakModeWordWrap;
lbl_endResult.numberOfLines = 0;
[lbl_endResult sizeToFit];
}
-(float) calculateHeightOfTextFromWidth:(NSString*)text : (UIFont*) withFont:(float)width :(UILineBreakMode)lineBreakMode
{
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
return suggestedSize.height;
}
It has helped me a lot.Hope it works for you.
Try
yourLabel.textAlignment = UITextAlignmentCenter;

How to have a page with long text that is wrapped automatically based on the phone screen

I am trying to make a book application. I am stucked with the text that can show long string. Basically, I tried to use UI Label, but it is only showing one line and the remaining of the text is cut.
Any idea what kind of UI that I should use to make a book? Thanks.
Set the numberOfLines for the UILabel to 0, to let it use as many lines as it needs.
You have to use UITextView for such purpose check
UITextView *aboutStable = [[UITextView alloc] init];
[aboutStable setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[aboutStable setText:#"Write your long text here............iphonemaclover is great"];
[aboutStable setTextColor:[UIColor grayColor]];
[aboutStable setBackgroundColor:[UIColor clearColor]];
[aboutStable setTextAlignment:UITextAlignmentCenter];
[aboutStable setFrame:CGRectMake(0, 302, 320, 79)];
[self addSubview:aboutStable];
And make it not editable so set
[aboutStable setUserInteractionEnabled:NO]
should do it
and if you need scrolling:
aboutStable.editable = NO;
or if you text is still more,then you can set scrollview in it too...
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 195, 280, 10)];
textView.text = #"your long text here";
textView.font = [UIFont fontWithName:#"Hevlatica" size:14];
[self.scrollView addSubview:textView];//add scrollview using Xib and set property of it.
CGRect descriptionFrame = textView.frame;
descriptionFrame.size.height = textView.contentSize.height;
textView.frame = descriptionFrame;
or you can check more detail here in this sample code
EDIT FOR DIFFERENT RETINA DISPLAY
CGRect screenRect = [[UIScreen mainScreen] bounds];
if (screenRect.size.height == 568.0f)
{
//condition for iphone 5 screen
}
else
{
//condition for retina display 3.5
}

UITextView not loading/showing the large text?

I have a simple UITextView in my login screen where I need to display Terms & conditions.I have a very large text in Terms and Conditions.In the interface builder I have added text to the UITextView. In the interface builder the text is getting showed properly. But when I run the application the UITextView is empty. If I give small text in the UItextView it is rendering properly but huge/large text is not getting displayed.
Here is the code.
- (IBAction)showTermsOfUse:(id)sender{
termsOfUseText.text = #"/***/";
termsOfUseText.scrollEnabled = YES;
[UIView beginAnimations:nil context:nil]; // begins animation block
[UIView setAnimationDuration:0.6]; // sets animation duration
[UIView setAnimationDelegate:self];
termsOfUse.frame = CGRectMake(0,0,320,416);
[UIView commitAnimations]; // commits the animation block. This Block is done.
}
I also had faced the same problem and i solved it my taking IBOutlet of UITextView and setting the value in the code like this
UITextView *txtView=[[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
[txtView setText:#"Your long text"];
[txtView setEditable:NO];
[self.view addSubview:txtView];
[txtView release];
Another option can be take a webview and load your contents in webview.
Create this UITextView programmatically
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(AsYouNeed)];
[textView setFont: [UIFont fontWithName:#"YourFontName" size:YourSize]];
textView.text = #"test my font size";
[textview setUserInteractionEnabled:TRUE];
[self.view addSubview:textView];
[textView release];
By giving the text programmatically....and
termsofUseText.text = #"MY LARGE TEXT GOES HERE...... "
termsOfUseText.scrollEnabled = YES;
termsOfUseText.userInteractionEnabled = YES;
termsOfUseText.editable = NO;

How to get the header view of a grouped table view?

I want to get all the views of a grouped table view to change the label color and to set the background color.
I found the answer, it's not possible to get the header view of a table view section. But you can implement the delegate tableView:viewForHeaderInSection: to recreate the header view and the label. The following code will give you the same header view and the exact label.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 5.5f, 300.0f, 30.0f)];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:16.5];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)];
view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
[view addSubview:label];
return view;
}
That's great you figured out your solution.
A couple of suggestions:
Don't hardcode the CGRect for the width of your frame, but rather use self.view.size.width for the width (e.g. in case you're in landscape orientation or if Apple ever introduces an iPhone with a different screen size);
You probably want to use autoresizingMask for both the label and the view that holds the label, so that they'll resize as the screen orientation changes, or make sure you invoke [self.tableview reloadData] on orientation changes; and
This is obviously a single line label ... if that works for you great, otherwise you'd want to use sizeWithFont:constrainedToSize:lineBreakMode to determine the height, both for creating the label/view as well as responding to tableView:heightForHeaderInSection:.
You also need to add the textColor:
label.textColor = [UIColor colorWithRed:0.265 green:0.294 blue:0.367 alpha:1.000];

Resources