How can I convert the characters in an NSString object to UILabel objects? - objective-c

I'm trying to figure out how to take the individual characters in an NSString object and create UILabels from them, with the UILabel text set to the individual character.
I'm new to Cocoa, but so far I have this...
NSString *myString = #"This is a string object";
for(int i = 0; i < [myString length]; i++)
{
//Store the character
UniChar chr = [myString characterAtIndex:i];
//Stuck here, I need to convert character back to an NSString object so I can...
//Create the UILabel
UILabel *lbl = [[UILabel alloc] initWithFrame....];
[lbl setText:strCharacter];
//Add the label to the view
[[self view] addSubView:lbl];
}
Aside from where I'm stuck, my approach already feels very hackish, but I'm a noob and still learning. Any suggestions for how to approach this would be very helpful.
Thanks so much for all your help!

You want to use -substringWithRange: with a substring of length 1.
NSString *myString = #"This is a string object";
NSView *const parentView = [self superview];
const NSUInteger len = [myString length];
for (NSRange r = NSMakeRange(0, 1); r.location < len; r.location += 1) {
NSString *charString = [myString substringWithRange:r];
/* Create a UILabel. */
UILabel *label = [[UILabel alloc] initWithFrame....];
[lbl setText:charString];
/* Transfer ownership to |parentView|. */
[parentView addSubView:label];
[label release];
}

Related

How can I word wrap with NSMutableAttributedString?

NSArray *myArray = #[#"1st:array1",
#"2nd:array2",
#"3rd:array3"
];
NSString *labelString = [myArray componentsJoinedByString:#"\n"];
In this codelabelStringcan be word wrapped.
But if use NSMutableAttributedString like this
NSAttributedString *resultString = [resultArray componentsJoinedByString:#"\n"];
it can't be joined by #"\n". Any other method is existed? Thanks.
It's not difficult. You just know one thing.
AttributedString can't have \n maybe. So you just put \n in NSString.
And just make NSAttributedString from this NSString.
Here this code. I hope this code help your work.
NSString *commentString;
NSMutableArray *resultArray = [[NSMutableArray alloc]initWithCapacity:50];
for (InstagramComment *comment in comments) {
commentString = [NSString stringWithFormat:#"%#:%#\n", comment.user.username, comment.text];
NSMutableAttributedString *styledCommentString = [[NSMutableAttributedString alloc]initWithString:commentString];
[resultArray addObject:styledCommentString];
}
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc]init];
for (int i = 0; i < resultArray.count; ++i) {
[resultString appendAttributedString:[resultArray objectAtIndex:i]];
} [cell.comment setAttributedText:resultString];

Changing the width of the space character in NSTextView

I’m trying to make a reader application to help a girl with reading difficulties. Some research shows that just changing the colors of the text, background and shadow can really help kids out so I’m trying to allow her to do that. It’s just a big NSTextView with buttons so she can change the font size, color, background color, shadow properties, letter spacing, line spacing and word spacing. I know you can do most of this just using Word but I’m trying to make it as intuitive/fun as possible for her.
The place where I could use a hand is in changing the size of the spacing between words. Currently I’m just searching for a string of spaces equal to the number of spaces I expect to be there and then replacing with more or less spaces it as follows:
- (IBAction)increaseSpacing:(id)sender{
NSInteger spacing = [[NSUserDefaults standardUserDefaults] integerForKey:#"wordSpacing"];
NSMutableString * oldString = [ NSMutableString stringWithCapacity:0];
NSMutableString * newString =[ NSMutableString stringWithCapacity:0];
for (int i = 0; i < spacing; i+=1) {
[oldString appendString:#" "];
}
[newString setString:oldString];
[newString appendString:#" "];
[[[textView textStorage] mutableString] replaceOccurrencesOfString:oldString
withString:newString options:0
range:NSMakeRange(0, [[textView textStorage] length])];
spacing += 1;
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInteger: spacing] forKey:#"wordSpacing"];
}
- (IBAction)reduceSpacing:(id)sender{
NSInteger spacing = [[NSUserDefaults standardUserDefaults] integerForKey:#"wordSpacing"];
if (spacing > 1) {
NSMutableString * oldString = [ NSMutableString stringWithCapacity:0];
NSMutableString * newString =[ NSMutableString stringWithCapacity:0];
for (int i = 0; i < spacing-1; i+=1) {
[newString appendString:#" "];
}
[oldString setString:newString];
[oldString appendString:#" "];
[[[textView textStorage] mutableString] replaceOccurrencesOfString:oldString
withString:newString options:0
range:NSMakeRange(0, [[textView textStorage] length])];
spacing -= 1;
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInteger: spacing] forKey:#"wordSpacing"];
}
}
This approach feels sloppy to me, especially when moving the cursor around with arrow keys. I could just change the font size of a space character when it’s typed, but that would also change the line height. Is there a way that I can just change the width of the space character? Thanks in advance for your help.
My eventual solution was to swap out spaces for blank images (blanks) that have the adjusted width.
Basic components:
a) Method to replace spaces with blanks
b) Method to replace blanks with spaces
c) NSValueTransformer for the NSTextView to do (a) for transformedValue and (b) for reverseTransformedValue
d) NSTextViewDelegate to do (a) when the text changes
e) Subclass NSTextView to do (b) on copied or cut text before sending to pasteboard
f) Action assigned to the stepper to make the size changes
Code for each part is below:
a) AppDelegate method to replace spaces with blanks
- (NSAttributedString * ) replaceSpacesWithBlanks:(NSString *)replaceString {
CGFloat imageWidth = [[NSUserDefaults standardUserDefaults] integerForKey:#"wordSpacing"];
NSImage * pic = [[NSImage alloc] initWithSize:NSMakeSize(imageWidth, 1.0f)];
NSTextAttachmentCell *attachmentCell = [[NSTextAttachmentCell alloc] initImageCell:pic];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
[attachment setAttachmentCell: attachmentCell ];
NSAttributedString *replacementString = [NSAttributedString attributedStringWithAttachment: attachment];
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:replaceString];
NSRange range = [[mutableString string] rangeOfString:#" "];
while (range.location != NSNotFound) {
[mutableString replaceCharactersInRange:range withAttributedString:replacementString];
range = [[mutableString string] rangeOfString:#" "];
}
return [[NSAttributedString alloc] initWithAttributedString: mutableString];
}
b) AppDelegate method to replace blanks with spaces
- (NSString * ) replaceBlanksWithSpaces:(NSAttributedString *)replaceAttributedString {
NSMutableAttributedString * mutAttrString = [[NSMutableAttributedString alloc] initWithAttributedString:replaceAttributedString];
for (int index = 0; index < mutAttrString.length; index += 1) {
NSRange theRange;
NSDictionary * theAttributes = [mutAttrString attributesAtIndex:index effectiveRange:&theRange];
NSTextAttachment *theAttachment = [theAttributes objectForKey:NSAttachmentAttributeName];
if(theAttachment != NULL) {
[mutAttrString replaceCharactersInRange:theRange withString:#" "];
}
}
return mutAttrString.string;
}
c) NSValueTransformer for the NSTextView to replace spaces with blanks for transformedValue and replace blanks with spaces for reverseTransformedValue
#implementation DBAttributedStringTransformer
- (id)init
{
self = [super init];
if (self) {
appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
}
return self;
}
+ (Class)transformedValueClass
{
return [NSAttributedString class];
}
+ (BOOL)allowsReverseTransformation
{
return YES;
}
- (id)transformedValue:(id)value
{
return [appDelegate replaceSpacesWithBlanks:value];
}
- (id)reverseTransformedValue:(id)value
{
return [appDelegate replaceBlanksWithSpaces:value];
}
d) NSTextViewDelegate to replace spaces with blanks when the text changes
#implementation DBTextViewDelegate
-(void)awakeFromNib {
appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
}
- (void)textViewDidChangeSelection:(NSNotification *)aNotification{
// Need to keep track of where the cursor should be reinserted
textLength = myTextView.string.length;
insertionPoint = [[[myTextView selectedRanges] objectAtIndex:0] rangeValue].location;
}
//replaces spaces with blank image and puts cursor back in correct position
- (void)textDidChange:(NSNotification *)aNotification{
NSInteger newTextLength = myTextView.string.length;
NSInteger newInsertionPoint = insertionPoint + newTextLength - textLength;
NSString * stringValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"textViewString"];
NSAttributedString * attrStringWithBlanks = [[ NSAttributedString alloc] initWithAttributedString:[appDelegate replaceSpacesWithBlanks:stringValue ]];
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithAttributedString:attrStringWithBlanks];
[myTextView.textStorage setAttributedString: mutableString];
//Put the cursor back where it was
[myTextView setSelectedRange:NSMakeRange(newInsertionPoint, 0)];
}
e) Subclass NSTextView to replace blanks with spaces on copied or cut text before writing to pasteboard
#implementation DBTextView
-(void)awakeFromNib {
appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
}
-(void) selectedTextToClipBoard{
NSRange selectedRange = [self selectedRange];
NSAttributedString * selectedText = [[self textStorage] attributedSubstringFromRange: selectedRange];
NSString * textWithoutBlanks = [appDelegate replaceBlanksWithSpaces:selectedText];
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
NSArray *copiedObject = [NSArray arrayWithObject:textWithoutBlanks];
[pasteboard writeObjects:copiedObject];
}
-(void) copy:(id)sender{
[self selectedTextToClipBoard];
}
-(void) cut:(id)sender{
[self selectedTextToClipBoard];
// Delete selected text so it acts like a cut
NSRange selectedRange = [self selectedRange];
[[self textStorage] deleteCharactersInRange:selectedRange];
}
f) Action assigned to the stepper to make the size changes
- (IBAction)changeWordSpacing:(id)sender {
CGFloat imageWidth = [[NSUserDefaults standardUserDefaults] integerForKey:#"wordSpacing"];
NSImage * pic = [[NSImage alloc] initWithSize:NSMakeSize(imageWidth, 1.0f)];
NSTextAttachmentCell *attachmentCell = [[NSTextAttachmentCell alloc] initImageCell:pic];
NSMutableAttributedString * mutAttrString = [[NSMutableAttributedString alloc] initWithAttributedString:[textView textStorage]];
for (int index = 0; index < mutAttrString.length; index += 1) {
NSRange theRange;
NSDictionary * theAttributes = [mutAttrString attributesAtIndex:index effectiveRange:&theRange];
NSTextAttachment *theAttachment = [theAttributes objectForKey:NSAttachmentAttributeName];
if(theAttachment != NULL) {
[theAttachment setAttachmentCell: attachmentCell ];
}
}
[[textView textStorage] setAttributedString:mutAttrString];
}
Also, NSTextView should be set to “Continuously Updates Value”
It is possible to adjust the font kerning specifically for space characters. Here is a simple way to do that using the new AttributedString:
var searchRange = text.startIndex..<text.endIndex
while let range = text[searchRange].range(of: " ") {
text[range].mergeAttributes(AttributeContainer([.kern: 10]))
searchRange = range.upperBound..<text.endIndex
}
You may use text[range].kern = 10 if you are using SwiftUI's Text view, but as of Xcode 13.4 the SwiftUI.Kern attribute created in that way will not convert properly for NSAttributedStrings.

How to view the entire content of an array in a label (xcode 4.1)

i'm programming in Obj-c with xcode4.1, i have an array with numbers in it, and i want to visualize all of them in a label...can anyone help me around this please?
thanks!
this is the code:
combinedString=[[NSMutableArray alloc] init];
NSString *finalStringLabel=#"";
for (i=0; i<=textLength; i++) {
//character coding
char myChar = [myString characterAtIndex:i];
NSString *myCharS=[NSString stringWithFormat:#"%c", myChar];
int asciiCode=[myCharS characterAtIndex:0];
NSString *asciiS=[NSString stringWithFormat:#"%i", asciiCode];
[combinedString addObject:asciiS];
}
finalStringLabel=[NSString stringWithFormat:#"", [combinedString componentsJoinedByString:#"."]];
myLabel.text=finalStringLabel;
[combinedString release];
}
You can use this
NSArray *yourArray;
NSString *createdString = [yourArray componentsJoinedByString:#" "];
myLabel.text = createdString;
As your array is combinedString,
combinedString=[[NSMutableArray alloc] init];
looks like you are providing values after this line or this is not a property (this is a local as you are releasing it later), and your code in not complete.
Anyways,
You don't need to create an empty string and then assign new object to it, need to do as :
myLabel.text=[combinedString componentsJoinedByString:#"."];
[combinedString release];
}

getting text from uilabel in objective-c

I have a project where I am trying to grab text from a uilabel that has been populated from a web service. I can grab and manipulate the text just fine but I need to send certain characters from the string to another web service call. I can not figure out how to grab the first, second and last characters in my string. I am both new to Objective-C as well as programming so any help would be much appreciated.
You can do it like this:
UILabel * l = [[UILabel alloc] init];
l.text = #"abcdef"; //set text to uilabel
[self.view addSubview:l];
NSString * text = l.text; //get text from uilabel
unichar first = [text characterAtIndex:0]; //get first char
unichar second = [text characterAtIndex:1];
unichar last = [text characterAtIndex:text.length -1];
If you need results as strings you can use:
NSString * firstAsString = [text substringWithRange:NSMakeRange(0, 1)]; //first character as string
or you can convert the unichar to string like this:
NSString * x = [NSString stringWithFormat:#"%C", last];
Per this it should be fairly easy:
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UILabel_Class/Reference/UILabel.html
textLabel.text = #"Foo";
Where textLabel is instance of UILabel

Dynamically Create Object Within Loop - Objective C

I'm looking for a way to dynamically create NSString objects in objective C based on how many of them I need (between 1 and 5). I then want to use those strings as names of objects which also are dynamically created;
Pseudo Code:
for (i=1, i <= number_of_characters, i++)
{
NSMutableString* theString = [NSMutableString character];
[theString appendString:[NSString stringWithFormat:#"%i ",i]];
UILabel *theString;
[theString release];
}
and I am hoping to get several UILabel objects named:
character1
character2
character3
and so on...
Thanks!
You can create UILabel objects on the fly, but you can't create variables at runtime. If you want to set the text of the label to theString, that's no problem:
NSMutableArray *labels = [NSMutableArray array];
for (i=1, i <= number_of_characters, i++)
{
NSMutableString* theString = [NSString stringWithFormat:#"%i ",i];
UILabel *label = [[UILabel alloc] initWithFrame:someCGRect];
label.text = theString;
[labels addObject:label];
[theString release];
}
Now you've got an array full of labels, each of which has a number as its text. The labels haven't been added to any view yet, so you'll want to take care of that.