Appending UIButton with NSString - iphone

I have this code to show some text in a textview from SQLite DB..
NSMutableString *combined = [NSMutableString string];
for(NSUInteger idx = 0; idx < [delegate.allSelectedVerseEnglish count]; idx++) {
[combined appendFormat:#" %d %#", idx, [delegate.allSelectedVerseEnglish objectAtIndex:idx]];
}
self.multiPageView.text = combined;
self.multiPageView.font = [UIFont fontWithName:#"Georgia" size:self.fontSize];
delegate.allSelectedVerseEnglish is the NSArray
multiPageView is the UITextView
i put the above loop function to get the Numbers according to the text,for example 1 hello 2 iPhone 3 iPad 4 mac etc etc..i just want UIButton between the text instead of 1 2 3 4 ..for example i want unbutton hello unbutton iPhone etc etc.because i need to make some touch events from it.how to do this?
Thanks in advance.

If you want to place UIButtons between some text in textview, there is no other way but to place it as a separate view just above. So you'll need to add spaces beneath those buttons, the amount of those you should calculate yourself, based on the size of your buttons.
So, if you would like yo see something like this:
Press here [UIButton] or here [Another UIButton],
your text string should look like this
Press here or here ,
So when you add the buttons on those places, it would look just like you wish.
UPDATE
Seems like we need some more code here, so here it is:
First, you'll need to calculate the size of a letter. Let's assume that it is 10 pixels height and 8 pixels.No, let's just call that letterHeight and letterWidth.Let's also assume that you want 64x10 pixels buttons. So, we will need 64/8=8 +2 spaces to out behind that button(2 to make borders around that)
So, here we go
NSMutableString *combined = [NSMutableString string];
int letterHeight = 10;
int letterWidth = 8;
for(NSString *verse in delegate.allSelectedVerseEnglish) {
[combined appendFormat:#" %#",verse];//10 spaces there
//You have to experiment with this, but idea is that your x coordinate is just proportional to the length of the line you are inserting your button in, and y is proportional to number of lines
int xCoordinate = [combined length]*letterWidth%(int)(self.multiPageView.frame.size.width);
int yCoordinate = [combined length]*letterWidth/(int)(self.multiPageView.frame.size.width)*letterHeight;
UIButton *newButton = [[UIButton alloc]initWithFrame:CGRectMake(xCoordinate,yCoordinate,64,10)];
[self.multiPageView addSubview:newButton];
}
self.multiPageView.text = combined;

Related

choosing a random image from a string that located in array with for loop

I want to write something, but I don't have any idea how to do it and where to start with it.
So, I have an array called imagesArray that contains 20 images of animals for example, lets say that the 5 first images of the array will be a images of : Rabbit.png, Horse.png, Lizard.png, Mouse.png and Dog.png.
So in the array that called wordsArray I will have in items in index range 0-4: "Rabbit", "Horse", "Lizard", "Mouse" and "Dog" and so on...
Also I have 4 UIButtons.
What I want the program to is, when the for loop is on item0, meaning that i=0, the image from imagesArray is Rabbit.png and the word from wordsArray is "Rabbit", I want to choose a random letter from the word "Rabbit" and display it once on one of the 4 UIButtons, the other 3 UIButtons will display any other letters but different letters.
I still didn't find a good way to do it. maybe its because I'm kinda new to Objective-C or programming at all..
How can I manage to do that?
EDIT
I have this code, but its not good because its working with UIImages instead of words and I dont know how to do it with words..
-(void)placeWordAndPictueOnScreen
{
// sets the letter in a random button
NSMutableArray * ButtonArray = [[NSMutableArray alloc]initWithObjects:btnLetter1,btnLetter2,btnLetter3,btnLetter4, nil];
int CorrectImg = random() % [ButtonArray count];
imgclick = CorrectImg;
UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgcounter]];
UIButton * btn = [ButtonArray objectAtIndex:CorrectImg];
[btn setImage:img forState:UIControlStateNormal];
[ButtonArray removeObjectAtIndex:CorrectImg];
// sets the other buttons with random letters
while ([ButtonArray count] != 0)// how many times u want to run this
{
int imgRand = random() % [LettersArray count]; //number for random image
int btnRand = random() % [ButtonArray count]; //number for random button
//get that random image
UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgRand]];
//get that random button
UIButton * button = [ButtonArray objectAtIndex:btnRand];
//put image on that button
[button setImage:img forState:UIControlStateNormal];
[ButtonArray removeObjectAtIndex:btnRand];
}
}
I believe that the next method will help you
-(NSMutableArray *)getStringInArray:(NSString *)string{
NSMutableArray *charsArray=[[NSMutableArray alloc]init];
while (![string isEqualToString:#""]) {
[charsArray addObject:[string substringToIndex:1]];
string=[string substringFromIndex:1];
}
return [charsArray autorelease];
}

Calculating enough text to fit within existing UILabel

I can't get some CoreText text wrapping code working for me; it's just too complicated. I'm going to try and go another route, which is to split my UILabel into two.
What I'm trying to achieve is to have my text appear to wrap around my fixed sized rectangular image. It'll always be the same dimensions.
So, when the UILabel next to the image fills up exactly, it'll create another UILabel below the image.
Now, how do I calculate the text in the first UILabel and have it fit nicely in the entire width of the UILabel, without being too short or cut off at the end?
Well, this ought to work to get the substring of the master string that will fit within the desired width:
//masterString is your long string that you're looking to break apart...
NSString *tempstring = masterString;
while (someLabel.bounds.size.width < [tempString sizeWithFont:someLabelLabel.font].width) {
NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[tempString componentsSeparatedByString:#" "]];
//Remove the last object, which is the last word in the string...
[tempArray removeLastObject];
//Recreate the tempString with the last word removed by piecing the objects/words back together...
tempString = #"";
for (int i=0; i < tempArray.count - 1; i++) {
tempString = [tempString stringByAppendingFormat:#"%# ", [tempArray objectAtIndex:i]];
}
//You must append the last object in tempArray without the space, or you will get an infinite loop...
tempString = [tempString stringByAppendingFormat:#"%#", [tempArray objectAtIndex:tempArray.count - 1]];
}
//Now do whatever you want with the tempString, which will fit in the width desired...
Of course, this is assuming you want the separation to occur using word wrapping. If you don't mind words themselves being cut apart (i.e. character wrap) in order to fully take up the desired width, do this instead:
NSString *tempstring = masterString;
while (someLabel.bounds.size.width < [tempString sizeWithFont:someLabelLabel.font].width) {
tempString = [tempString substringToIndex:tempString.length - 1];
}
//Now do whatever you want with the tempString, which will fit in the width desired...
In order to get the remaining piece of the string left over, do this:
NSString *restOfString = [masterString substringFromIndex:tempString.length];
Hope this helps. I have to admit that I haven't properly tested this code yet, though I've done something similar in the past...
Try below link its will help you.
If you want to create a "link" on some custom text in your label, instead of using a WebView as #Fabian Kreiser suggested, you sould use my OHAttributedLabel class (you can find it this link)
See the sample code provided on my github repository: you can use my addCustomLink:inRange: method to add a link (with a customized URL) to a range of text (range that you could determine by iterating over every occurrences of the word "iPhone" in your text very easily). Then in the delegate method on OHAttributedLabel, you can catch when the link is tapped and act accordingly to do whatever you need.

How to know the displayed text in UILabel?

I have an UIView containing two UILabels, in order to display a string.
The first UILabel has a fixed size, and if the string is too long and can't hold in this UILabel, I want to display the maximum characters I can in the first UILabel, and display the rest of the string in the second UILabel.
But to make this, I must know the exact part of the string displayed in the first UILabel, which is not easy because of the randomness of the string and the linebreaks.
So, is there a way to get just the text displayed in the first UILabel, without the truncated part of the string?
if ([_infoMedia.description length] > 270) {
NSRange labelLimit = [_infoMedia.description rangeOfString:#" " options:NSCaseInsensitiveSearch range:NSMakeRange(270, (_infoMedia.description.length - 270))];
_descTop.text = [_infoMedia.description substringToIndex:labelLimit.location];
_descBottom.text = [_infoMedia.description substringFromIndex:(labelLimit.location+1)];
} else {
_descTop.text = _infoMedia.description;
_descBottom.text = #"";
}
Okay that's a late answer but maybe it could help someone. The code above is approximatively the solution I used in my app.
_descTop is my first label and _descBottom is the second label. 270 is a constant equivalent to a little less than the average maximum number of characters displayed in my first label, _descTop. I calculated it by hand, trying with many different strings, maybe there's a better way to do that but this worked not bad.
If the string I want to display (_infoMedia.description) is larger than 270 characters, I isolate the first 270 characters plus the end of the next word in the string (by searching the next space), in the case where the 270 characters limit would cut the string in the middle of a word. Then I put the first part of the string in my first label, and the second part in the second label.
If not, I only put the globality of the string in the first label.
I know that's a crappy solution, but it worked and I didn't found any better way to do that.
Following code might help you in getting what you want!!
//If you want the string displayed in any given rect, use the following code..
#implementation NSString (displayedString)
//font- font of the text to be displayed
//size - Size in which we are displaying the text
-(NSString *) displayedString:(CGSize)size font:(UIFont *)font
{
NSString *written = #"";
int i = 0;
int currentWidth = 0;
NSString *nextSetOfString = #"";
while (1)
{
NSRange range;
range.location = i;
range.length = 1;
NSString *nextChar = [self substringWithRange:range];
nextSetOfString = [nextSetOfString stringByAppendingString:nextChar];
CGSize requiredSize = [nextSetOfString sizeWithFont:font constrainedToSize:CGSizeMake(NSIntegerMax, NSIntegerMax)];
currentWidth = requiredSize.width;
if(size.width >= currentWidth && size.height >= requiredSize.height)
{
written = [written stringByAppendingString:nextChar];
}
else
{
break;
}
i++;
}
return written;
}
#end

Loop through labels iPhone SDK

Ok I have 8 labels and I want to loop through them but am having no luck.
This is what I have tried.
for (int i; i = 0; i < 10; i++)
{
double va = [varible1.text doubleValue] + i;
int j = 0 + I
label(j).text= [[NSString alloc]initWithFormat:#"%2.1f", va];
}
This errors out. My labels are named like this label0, label1, label2
Any help would be appreciated.
label(j) is NOT equivalent to label0, label1, etc.
You should create an NSArray of labels, then you can access them with [arrayOfLabels objectAtIndex:j]. If you're not sure what this means, please read the documentation about NSArray...
You should maybe add all your labels to a C array, probably in -viewDidLoad
UILabel* labels[] = { label0, label1, label2, ... };
(not entirely sure about the syntax)
and then access them like
labels[i].text = ...
By the way, I think you're leaking memory here:
labels[i].text = [[NSString alloc]initWithFormat:#"%2.1f", va];
initWithFormat: will return a string with a retain count of 1. labels[i].text will retain that value again. You should release the string after setting the label's text. I'd probably just autorelease it here:
labels[i].text = [[[NSString alloc]initWithFormat:#"%2.1f", va] autorelease];
or use stringWithFormat (which returns an autoreleased string):
labels[i].text = [NSString stringWithFormat:#"%2.1f", va];
for (UILabel *lbl in self.view.subviews)
{
[lbl setFont:[UIFont fontWithName:#"AppleGothic" size:22]];
}
it will change all the labels in your ViewController by just giving tags to labels.
If you cannot or do not want to put your labels in an array, you could iterate through the UIViews using the tag field as an index. You store the index numbers in them (either through IB or programatically) and then get each label using: (UIView *)viewWithTag:(NSInteger)tag.
See below (set theView to the view your labels reside in):
for (int i; i = 0; i < 10; i++)
{
double va = [varible1.text doubleValue] + i;
UILabel * label = [theView viewWithTag: i];
label.text= [[NSString alloc]initWithFormat:#"%2.1f", va];
}

Reuse Cocos2d CocosNodes

I am trying to create a cool score counter in my iPhone game, where I created the digits 0 to 9 in photoshop and I want to update the score every second.
What I am doing now is the following:
In my init I load all the digit sprites into an array, so that the array has 10 items.
I created a method which breaks down the current score (eg. 2000) into single digits and gets the sprites from the array and after that adds them to a parent CocosNode* object.
Every second I get the parent CocosNode by it's tag and replace it with the new parent object.
Currently I am already running into problems with this, because the score 2000 uses the 0-digit three times and I cannot re-use sprites.
- (CocosNode*) createScoreString:(int) score
{
NSLog(#"Creating score string : %d", score);
NSString* scoreString = [NSString stringWithFormat:#"%d", score];
int xAxes = 0;
CocosNode* parentNode = [[Sprite alloc] init];
for (NSInteger index = 0; index < [scoreString length]; index++)
{
NSRange range;
range.length = 1;
range.location = index;
NSString* digit = [scoreString substringWithRange:range];
Sprite* digitSpriteOriginal = [self.digitArray objectAtIndex:[digit intValue]];
Sprite* digitSprite = [digitSpriteOriginal copy];
[digitSprite setPosition:cpv(xAxes, 0)];
xAxes += [digitSprite contentSize].width - 10;
[parentNode addChild:digitSprite];
}
return parentNode;
}
Am I handling this the right way within cocos2d or is there some standard functionality for this? Also, if this is correct, how can I 'reuse' the sprites?
I believe that you want to use the LabelAtlas class, you'll only need to provide a compatible bitmap (like one the fps counter uses).