wrapping text of a UITextView (line break mode) - ios

A UITextView (kind of modal : it is shown when pressing on a button) appears for the user to collect what he wants to write in another UITextView which is fixed.
I resize the UITextView's height (the one which is fixed), and put in it the text that has been entered by the user in the other (modal) UITextView.
But, instead of doing the line break (as it did in the modal UITextView), the fixed UITextView does not wrap the text...
How can I make the fixed UITextView wrap the text ?
Here is my code :
textsToDisplay[index] = [enterText text];
NSInteger _stringTotalLength=[[enterText text] length];
NSMutableAttributedString *attSt=[[NSMutableAttributedString alloc] initWithString:[enterText text]];
[attSt addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Helvetica" size:15.0]
range:NSMakeRange(0, _stringTotalLength)];
float height3 = ceil(attSt.size.height);
UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if(UIInterfaceOrientationIsPortrait(interfaceOrientation)){
cellSizes[index] = CGSizeMake(screenWidth-6,height3+10);
}else if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
cellSizes[index] = CGSizeMake(screenHeight-25,height3+10);
}
I store the text which was entered by the user in textsToDisplay which is a table of NSString. I am using a UICollectionView whose cells contain the fixed UITextView and I set the text in the following method :
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSMutableAttributedString *attSt=[[NSMutableAttributedString alloc] initWithString:textsToDisplay[index]];
NSInteger _stringTotalLength=[textsToDisplay[index] length];
[attSt addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Helvetica" size:15.0]
range:NSMakeRange(0, _stringTotalLength)];
cell.textView.attributedText =attSt;
I create the uitextview for entering code like this :
float width = 500.0f;
enterText = [[UITextView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-(width)/2, self.view.frame.size.height/2-200, width, 400)];
NSMutableAttributedString *attSt=[[NSMutableAttributedString alloc] initWithString:questionCell.textView.text];
NSInteger _stringTotalLength=[questionCell.textView.text length];
[attSt addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Helvetica" size:15.0]
range:NSMakeRange(0, _stringTotalLength)];
enterText.attributedText = attSt;
enterText.tag = 92;
enterText.backgroundColor = [UIColor whiteColor];
enterText.alpha = 1;
enterText.delegate = self;
[self.view addSubview:enterText];
and here is how I create the uitextview in a cell :
textView = [[UITextView alloc]initWithFrame:CGRectMake(50, 0, widthLabel-50, 50)];
textView.userInteractionEnabled = YES;
textView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
textView.backgroundColor = [UIColor clearColor];
and I configure it like this :
cell.textView.frame = CGRectMake(50, 0, cellSizes[index].width-50, cellSizes[index].height);

I ended up using a uilabel in each uicollectionviewcell because it is way too complex to do the line break with a uitextview.

Related

Changing the color of a buttons text in iOS (objective-c)

I want to change the color of the text in my button to be blue on load. I also need only the first 9 letters (length of userName) of the buttons text to be blue, not all of the text. How do I do this?
Example:
This above image shows "#LisaLisa is following you". This is the buttons text. How do I make just "#LisaLisa" to be blue, with "is following you" staying black?
UIButton *someButton = [UIButton buttonWithType:UIButtonTypeSystem];
NSString *someUsername = #"#LisaLisa";
NSString *buttonText = [NSString stringWithFormat:#"%# is following you.", someUsername];
NSRange rangeToHighlight = [buttonText rangeOfString:someUsername];
NSDictionary *defaultAttributes = #{NSForegroundColorAttributeName: [UIColor blackColor]};
NSDictionary *highlightedAttributes = #{NSForegroundColorAttributeName: [UIColor blueColor]};
NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:buttonText attributes:defaultAttributes];
[attributedTitle addAttributes:highlightedAttributes range:rangeToHighlight];
[someButton setAttributedTitle:attributedTitle forState:UIControlStateNormal];
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
UIColor *color1 = [UIColor redColor];
UIColor *color2 = [UIColor blueColor];
UIFont *font1 = [UIFont fontWithName:#"HelveticaNeue" size:20.0f];
UIFont *font2 = [UIFont fontWithName:#"HelveticaNeue-Light" size:20.0f];
NSDictionary *dict1 = #{NSFontAttributeName:font1,
NSForegroundColorAttributeName:color1 }; // Added line
NSDictionary *dict2 = #{NSFontAttributeName:font2,
NSForegroundColorAttributeName:color2 }; // Added line
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:senderName attributes:dict1]];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:#"posted to" attributes:dict2]];
[cell.profileIDButton setAttributedTitle:attString forState:UIControlStateNormal];
[[cell.profileIDButton titleLabel] setNumberOfLines:0];
[[cell.profileIDButton titleLabel] setLineBreakMode:NSLineBreakByWordWrapping];
This answer worked for me. I wasnt able to test Andre's answers yet.
UILabel * myLabel = [[UILabel alloc] init];//used for whole string
myLabel.numberOfLines = 0;
NSString * myUserName = #"#LisaLisa";//used for userName
//add button on UserName
UIButton * muButton = [[UIButton alloc] init];
myLabel.text = [NSString stringWithFormat:#"%#", myUserName];
myLabel = [self setDynamicLableFrame:myLabel fontSize:fontSize Width:width];
//Here width is your Label's Width. Because we have to make sure that our, our label's width is not greater than our device's width and fontSize is label's fontSize
muButton.frame = myLabel.frame;
myLabel.text = [NSString stringWithFormat:#"%# is following you", myUserName];
myLabel = [self setDynamicLableFrame:myLabel fontSize:fontSize Width:width];//used for making dynamic height of label
//For changing color of UserName
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: myLabel.attributedText];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, myUserName.length)];
[myLabel setAttributedText: text];
Following method is used for making label's Dynamic Height & Width. Because we have to set Button's frame only on UserName ("LisaLisa").
//for setting the dynamic height of labels
-(UILabel *)setDynamicLableFrame:(UILabel*)myLabel fontSize:(float)size Width:(float)Width
{
CGSize possibleSize = [myLabel.text sizeWithFont:[UIFont fontWithName:REGULER_FONT size:size] constrainedToSize:CGSizeMake(300, 9999) lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = myLabel.frame;
newFrame.size.height = possibleSize.height;
if (possibleSize.width < Width) {
newFrame.size.width = possibleSize.width;
}else{
newFrame.size.width = Width;
}
myLabel.frame = newFrame;
return myLabel;
}
Hope, This is what you're looking for. Any concern get back to me.

UILabel won't register line spacing property

For some reason this code (the bold text in particular) doesn't change the line spacing of the text at all:
UIFont* customFont = [UIFont fontWithName:#"BebasNeue" size:70];
NSString * text = #"Their \nIdeas";
**NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
paragrahStyle.lineSpacing = 30;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [text length])];**
UILabel *lbl1 = [[UILabel alloc] init];
[lbl1 setFrame:CGRectMake(120, 70, viewWidth, 180)];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.textColor = grayColor;
lbl1.numberOfLines = 2;
lbl1.attributedText = attributedString;
lbl1.userInteractionEnabled = NO;
lbl1.text = text;
[lbl1 setFont:customFont];
[view addSubview:lbl1];
[lbl1 setTransform:CGAffineTransformMakeRotation(0.35)];
What am I doing wrong?
The issue is with this line ,
lbl1.text = text;
You are assigning a non attributed string just after assigning the attributed string which contains all line spacing data. Remove above line then your code will work.
And if you are using a large value for line spacing, make sure your label's height is enough to display the second line.

UILabel with different fonts

I have this string that I want to display in a label:
NSString *criticsScore=[NSString stringWithFormat:#"%#\%%",[dict objectForKey:#"critics_score"]];
_criticRating.text=criticsScore;
I want to set a small font for \%% and a large font for [dict objectForKey:#"critics_score"]];
Is this possible?
You Need to use your own control for drawing an NSAttributedString, like TTTAttributedLabel.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"Blah1:blah-blah%d. Blah2:-%d%%", [currentCoupon.couponPrice intValue],[currentCoupon.couponDiscountPercent intValue]];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(0,30)];/// Define Range here and also BackGround color which you want
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,30)];/// Define Range here and also TextColor color which you want
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
lblWithText.attributedText = str;
Above Code I got From How to use multiple font stylings on a single string inside a label?
Read this post. It is about NSAttributedStrings. I think that is what you need.
You would have to do it with two UILabels. You would set the first label to be all of the text excpt the \%%, and get the size of that label using sizeWithFont: on the text that goes in that label. Then set the second label to start at the end of that label's frame.
So, it would look something like this, changing the coordinates based on where you want the labels:
NSString *criticsScore = [NSString stringWithFormat:#"%#",[dict objectForKey:#"critics_score"]];
NSString *str2 = #"\%%";
UIFont *criticsFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
UIFont *font2 = [UIFont systemFontOfSize:12.0];
//Get the sizes of each text string based on their font sizes.
CGSize criticsSize = [criticsScore sizeWithFont:criticsFont];
CGSize size2 = [str2 sizeWithFont:font2];
int x = 0;
int y = 0;
//The first label will start at whatever x and y are.
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(x,y,criticsSize.width,criticsSize.height)];
[label1 setFont:criticsFont];
//Create a second label with the x starting at x+criticsSize.width;
//The y will start at y+criticsSize.height-size2.height, so that it will be aligned with the bottom.
//Change these to align it differently.
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(x+criticsSize.width,y+criticsSize.height-size2.height,size2.width,size2.height)];
[label2 setFont:font2];
[self.view addSubview:label1];
[self.view addSubview:label2];

UITextField underlines from NSAttributedString are only 1 pixel high?

The label (bottom of the picture) and the text field (top) have the same same attributedText. But look at the underlines. The ones in the text field are only one pixel high. This looks terrible. Does anyone know what is causing this or how to prevent it?
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UITextField* textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 600, 200)];
NSMutableAttributedString* string = [[NSMutableAttributedString alloc]initWithString:#"The quick brown fox jumps"];
NSNumber* underlineNumber = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
UIFont* font = [UIFont systemFontOfSize: 50];
[string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, string.length)];
for (NSInteger i=0; i<20; i++) {
if (i%3==0) {
[string addAttribute:NSUnderlineStyleAttributeName value:underlineNumber range:NSMakeRange(i, 1)];
}
}
textField.backgroundColor = [UIColor whiteColor];
textField.attributedText = string;
[self addSubview:textField];
UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(100, 400, 600, 200)];
label.attributedText = string;
label.font = font;
label.backgroundColor = [UIColor whiteColor];
[self addSubview:label];
}
return self;
}
The label uses a custom rendering style to draw the underline which is unfortunately distinct from the one used by UITextField, which uses WebKit to render when editing and Core Text to render when it's static. Please file a bug with bugreporter.apple.com. Thanks!

Is is possible to change a UISearchBar placeholder's alignment?

I am going to need to show the UISearchBar in different alignments because of different input languages.
I saw this answer, but I can't find where is it that you actually align the text to the right on a UISearchBar.
Any ideas?
Thanks!
This is what I've done:
for (UIView *subView in self.subviews){
if ([subView isKindOfClass:[UITextField class]]) {
UITextField *text = (UITextField*)subView;
text.textAlignment = UITextAlignmentRight;
text.rightViewMode = UITextFieldViewModeAlways;
}
}
If you also want to move the magnifying glass icon, you can do this:
text.leftView = nil;
text.rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"search_icon.png"]];
But you will have to provide the search_icon.png image.
Here is the solution
UITextField *searchTextField = [searchBar valueForKey:#"_searchField"];
UILabel *placeholderLabel = [searchTextField valueForKey:#"_placeholderLabel"];
[placeholderLabel setTextAlignment:NSTextAlignmentLeft];
To set attributed placeholder text to achieve left aligned placeholder, try this code...
//Step1 : Make blank attributed string
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:#""];
//Step2 : Append placeholder to blank attributed string
NSString *strSearchHere = #"Search here...";
NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subString = [[NSAttributedString alloc] initWithString:strSearchHere attributes:attributes];
[attributedString appendAttributedString:subString];
//Step3 : Append dummy text to blank attributed string
NSString *strLongText = #"LongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongText";
NSDictionary * attributesLong = [NSDictionary dictionaryWithObject:[UIColor clearColor] forKey:NSForegroundColorAttributeName];
NSAttributedString * subStringLong = [[NSAttributedString alloc] initWithString:strLongText attributes:attributesLong];
[attributedString appendAttributedString:subStringLong];
//Step4 : Set attributed placeholder string to searchBar textfield
UITextField *searchTextField = [searchBarr valueForKey:#"_searchField"];
searchTextField.attributedPlaceholder = attributedString;
searchTextField.leftView = nil; //To Remove Search icon
searchTextField.textAlignment = NSTextAlignmentLeft;

Resources