I have task to develop the application with words counting and display in runtime generated uiscrollview with uilabel as subview.
The process is like when user will load page at that time the 1000 of word will fill in the rutime generated uilabel with scrollview.And all thing is set from runtime. but it the application we have one button to add the current uilabel text on button click.
and the words are coming random from database. when i click on the button it gives me the different word. from scroll view displayed word.
Following is my code to fill the data in uilabel with scrollview :
wordName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 2)];
[wordNameArray addObject:wordName];
int i = 0;
for (i = 1; i <= kNumImages; i++)
{
randomN = [wordNameArray objectAtIndex:arc4random() % [wordNameArray count]];
UIImage *image = [UIImage imageNamed:#"word_bg.png"];
word = [[UILabel alloc]initWithFrame:CGRectMake(15,12,250,120)];
[word setFont:[UIFont fontWithName:#"Helvetica-Bold" size:36.0f]];
word.textColor = [UIColor whiteColor];
word.lineBreakMode = UILineBreakModeWordWrap;
word.numberOfLines = 2;
word.textAlignment = UITextAlignmentCenter;
word.backgroundColor = [UIColor clearColor];
[word setText:randomN];
lblWord.text = word.text;
word.tag = i;
NSLog(#"tag no:%d",word.tag);
imageView = [[UIImageView alloc] initWithImage:image];
[imageView addSubview:word];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
//NSLog(#"%#",word.text);
//NSLog(#"%#",lblWord.text);
// [scrollView1 addSubview:l];
[scrollView1 addSubview:imageView];
touchToSee.hidden = TRUE;
[imageView release];
}
[self layoutScrollImages];
Following is my scroll event to get the word from label but it is giving me last word from array:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
touchToSee.hidden = TRUE;
NSLog(#"word-%#",word.text);
}
And other when i click on button i am not getting the perfect work so for that following is my code:
NSString *getword = [NSString stringWithFormat:#"%#",word.text];
NSLog(#"lblCountdownBackward:%#",word.text);
So please help me and provide me some sample code for it if it possible.
thanks in advance.
You appear to be creating lots of word objects, and adding them to the screen.
In your for loop, you perform your code upto kNumImages. And in each run, the word Object is replace with a new one.
So when you get the word later on, it will be the very last word object you created (hence the last word).
To get arround this you could use an NSMutableArray and keep adding a new UILabel object to that (instead of creating the word object). And then later on do something like
[array objectAtIndex:0].text;
Related
I have to present the currency and the price in a UILabel. In one label, but using different font sizes. Now it looks like this:
... and I did it overriding drawTextInRect: like this:
- (void)drawTextInRect:(CGRect)rect{
CGSize textSize = [self.text sizeWithFont:self.font];
textSize.width -= textSize.width/12;
CGRect analogRect = CGRectMake(0, 0, textSize.width, self.frame.size.height);
CGPoint centrino = self.center;
self.frame = analogRect;
self.center = centrino;
NSString *currency = [self.text substringWithRange:NSMakeRange(0, 3)];
NSString *amount = [self.text substringWithRange:NSMakeRange(3, self.text.length - 3)];
self.text = currency;
self.textAlignment = UITextAlignmentLeft;
self.font = [UIFont fontWithName:#"Helvetica-Bold" size:30.];
self.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
[super drawTextInRect:analogRect];
self.text = amount;
self.textAlignment = UITextAlignmentRight;
self.font = [UIFont fontWithName:#"Helvetica-Bold" size:40.];
[super drawTextInRect:analogRect];
}
Nice, isn't it?
But I need to align the currency and the price at the bottom, like this:
As you can see, I need to force "EUR" to go lower, because its size is smaller and it's centered, so it looks higher.
Please suggest a way to do this.
Thanks in advance!
NOTE:
Using 2 different labels is not good for me. I gotta do it in a single label.
Two ideas: 1) Since you're subclassing UILabel, you could put a second label for the currency type within the subclass' implementation, and your view would still think there's only a single label. 2) Since the NDA is lifted today on iOS 6, I'll suggest taking a look at attributed strings. Oh, and +1 for writing 'a UILabel' and not 'an UILabel.'
Ok, guys, thanks to everybody for your fast answers, but I have no time for researches, so I have found a newbie solution.
I feel shame but here is it:
- (void)setCurrencyAndPrice{
//set the labels' texts
[label_currency setText:#"EUR"];
[label_amount setText:#"12.34"];
//set the sizes to fit the content
[label_currency sizeToFit];
[label_amount sizeToFit];
//read the new frame of the labels
CGRect curRect = label_currency.frame;
CGRect amoRect = label_amount.frame;
//adjust the position of the price to the top-right
[label_amount setFrame:CGRectMake(320 - amoRect.size.width - 10, 0, amoRect.size.width, amoRect.size.height)];
//read again the price frame
amoRect = label_amount.frame;
//stick the currency to the price, spacing 10 pixels
[label_currency setFrame:CGRectMake(amoRect.origin.x - curRect.size.width - 10, 11, curRect.size.width, curRect.size.height)];
}
As you can see, nothing to override, just using 2 different labels - exactly what I did NOT want to do, but the time runs faster that I am coding.
Cheers!
P.S.: Although I have found the solution for myself, I like #MichaelMangold' idea, so I accept his answer.
Instead of using two UILabels, you can have one label with multiple text fonts styles and colors. Here is an example, may be that might help you :
UILabel *customLbl = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 25)];
customLbl.backgroundColor = [UIColor yellowColor];
[self createTwoTextStyleInSingleUILabel:customLbl];// custom method calling
[self.view addSubview:customLbl];
Custom Method goes like this :
Before applying this method, add QuartzCore framework (needed for CALayers), and CoreText framework(needed for the attributed string.) in your project.
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
- (void)createTwoTextStyleInSingleUILabel: (UILabel *) myLabel{
NSString *firstText = NSLocalizedString(#"First text:", nil);
NSString *secondText = [NSString stringWithFormat:#"%# %#",firstText,#"Second text"];
CATextLayer *myLabelTextLayer;
/* Create the text layer on demand */
if (!myLabelTextLayer) {
myLabelTextLayer = [[CATextLayer alloc] init];
myLabelTextLayer.backgroundColor = [UIColor clearColor].CGColor;
myLabelTextLayer.wrapped = NO;
CALayer *layer = myLabel.layer; //assign layer to your UILabel
myLabelTextLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
myLabelTextLayer.contentsScale = [[UIScreen mainScreen] scale];
myLabelTextLayer.alignmentMode = kCAAlignmentCenter;
[layer addSublayer:myLabelTextLayer];
}
/* Create the attributes (for the attributed string) */
// customizing first string
CGFloat fontSize = 16;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
CTFontRef ctBoldFont = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
CGColorRef cgColor = [UIColor redColor].CGColor;
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)ctBoldFont, (id)kCTFontAttributeName,
cgColor, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctBoldFont);
// customizing second string
UIFont *font = [UIFont systemFontOfSize:16];
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
CGColorRef cgSubColor = [UIColor blackColor].CGColor;
NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)ctFont, (id)kCTFontAttributeName,cgSubColor, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctFont);
/* Create the attributed string (text + attributes) */
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:secondText attributes:attributes];
float lengthOfSecondString = 12.0; // length of second string including blank space inbetween text, space in front , space after text.. Be careful, your app may crash here if length is beyond the second text length (lengthOfSecondString = text length + blank spaces)
[attrStr addAttributes:subAttributes range:NSMakeRange(firstText.length, lengthOfSecondString)];
// you can add another subattribute in the similar way as above , if you want change the third textstring style
/* Set the attributes string in the text layer :) */
myLabelTextLayer.string = attrStr;
myLabelTextLayer.opacity = 1.0; //to remove blurr effect
}
This library will work for you https://github.com/AliSoftware/OHAttributedLabel
I'd build a UIView subclass called ValueUnitsLabel. Give it two labels and let it control framing, font sizes etc. It can also be smart about reading NSLocale.
I have a UIScrollView which scrolls only horizontally. I have a situation where I have views filled by array in UIScrollView. There are three views which altogether make one single component in UIScrollView (there are many such components). Component contains :
UILabel
UIButton
UIView (for underlying text)
I have placed two arrow keys(left and right) at the ends of UIScrollView. On touching left arrow I am shifting one position left (with complete string to display) in UIScrollView and one position right (with complete string to display) in case of right arrow button.
Till now I am able to perform left arrow action. But I have no idea how to perform right arrow touch and how to display complete string to touching arrow keys if only part of that string is being displayed.
I know it is weird that I have a UIScrollView and still want to add arrow keys to move it. But can't help it. This is client's requirement. The following is how I implemented left arrow action:
-(IBAction) onClickLeftArrow
{
NSLog(#"BUTTON VALUE : %i",iButtonValue);
if(iButtonValue <= [m_BCListArray count]) {
NSArray *arr = [scrollDemo subviews];
for(int j = 0; j < [arr count]; j++) {
UIView *view1 = [arr objectAtIndex:j];
[view1 removeFromSuperview];
}
XX = 5.0;
int tagcount = [m_BCListArray count]-iButtonValue;
NSLog(#"%#",m_BCListArray);
for(int i = iButtonValue; i >= 1; i--)
{
UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(XX, 6, 120, 26)];
blabel.text = [m_BCListArray objectAtIndex:[m_BCListArray count]-i];
blabel.backgroundColor = [UIColor clearColor];
blabel.textColor = [UIColor whiteColor];
blabel.font = [UIFont systemFontOfSize:14];
[scrollDemo addSubview:blabel];
//underline code
CGSize expectedLabelSize = [[m_BCListArray objectAtIndex:[m_BCListArray count]-1] sizeWithFont:blabel.font constrainedToSize:blabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = blabel.frame;
newFrame.size.height = expectedLabelSize.height;
blabel.frame = CGRectMake(blabel.frame.origin.x, blabel.frame.origin.y, expectedLabelSize.width+10, expectedLabelSize.height);
blabel.numberOfLines = 1;
[blabel sizeToFit];
int width=blabel.bounds.size.width;
int height=blabel.bounds.size.height;
UIButton *btnContent = [UIButton buttonWithType:UIButtonTypeCustom];
[btnContent addTarget:self action:#selector(SelectButton:)forControlEvents:UIControlEventTouchDown];
btnContent.tag = tagcount+1;
btnContent.frame=CGRectMake(XX, 2.0, width+10, height);
[scrollDemo addSubview:btnContent];
scrollDemo.contentSize = CGSizeMake(XX+50, 32);
//scrollDemo.contentSize = CGSizeMake(expectedLabelSize.width,expectedLabelSize.height);
UIView *viewUnderline=[[UIView alloc] init];
viewUnderline.frame=CGRectMake(XX, 26, width, 1);
viewUnderline.backgroundColor=[UIColor whiteColor];
[scrollDemo addSubview:viewUnderline];
[viewUnderline release];
scrollDemo.contentSize = CGSizeMake(XX+width+10, 32);
XX = XX + width+10;
iRight = iRight + 1;
tagcount ++;
// iRight --;
}
}
iButtonValue = iButtonValue+1;
}
Set the contentOffset of UIScrollView on the Button click action and u'll get your desired effect.
I need to create a horizontal UIScrollView which to hold hundreds of thumbnail images, just like a slide of thumbnails.
For example, there will be 10 thumbnails showing in a single screen, each of them are horizontally adjacent to each other.
My problem is that I don't know how to make a horizontal UIScrollView to hold the multiple thumbnails which showing at the same time ?
A sample photo is as below. See the bottom part of the screen.
Thanks.
You can add all the thumbnails programatically to your scrollview and use the setContentSize method of UIScrollView. you have to pass 2 values in contentOffset. 1 for width and 1 for height. Please follow link to explore more on this. If you need further help please leave a comment.
Hope it helps.
Please consider Following example.
- (void)setupHorizontalScrollView
{
scrollView.delegate = self;
[self.scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = NO;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
NSInteger tot=0;
CGFloat cx = 0;
for (; ; nimages++) {
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (tot==15) {
break;
}
if (4==nimages) {
nimages=0;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = 40;
rect.size.width = 40;
rect.origin.x = cx;
rect.origin.y = 0;
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += imageView.frame.size.width+5;
tot++;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
I suggest you to look at nimbus
Check out bjhomer's HSImageSidebarView project. It lets you load a scrollview horizontally or vertically and load in the images. Super easy to implement.
First of all, at storyboard drag and drop the scroll view and make the outlet of scrollview named scrollView. Two array one is mutable and one is immutable.
#property(nonatomic,strong)IBOutlet UIScrollView *scrollView;
#property(nonatomic,strong)NSMutableArray *images;
#property(nonatomic,strong)NSArray *imagesName;
The immutable array only store the images which we want to show on the scroll view.Make sure UIscrollview delegate is defined.
In viewcontoller.m file in didload function do following code:
imagesName = [[NSArray alloc]initWithObjects:#"centipede.jpg",#"ladybug.jpg",#"potatoBug.jpg",#"wolfSpider.jpg", #"ladybug.jpg",#"potatoBug.jpg",#"centipede.jpg",#"wolfSpider.jpg",nil];
// mutable array used to show the images on scrollview dynamic becaus after one
// image when scroll other will come
images = [[NSMutableArray alloc]init];
scrollView.delegate = self;
scrollView.scrollEnabled = YES;
int scrollWidth = 120;
scrollView.contentSize = CGSizeMake(scrollWidth,80);
int xOffset = 0;
//the loop go till all images will load
for(int index=0; index < [imagesName count]; index++)
{
UIImageView *img = [[UIImageView alloc] init];
// make the imageview object because in scrollview we need image
img.frame = CGRectMake(5+xOffset, 0, 160, 110);
// the offset represent the values, used so that topleft for each image will
// change with(5+xOffset, 0)and the bottomright(160, 110)
NSLog(#"image: %#",[imagesName objectAtIndex:index]);
img.image = [UIImage imageNamed:[imagesName objectAtIndex:index]];
// The image will put on the img object
[images insertObject:img atIndex:index];
// Put the img object at the images array which is mutable array
scrollView.contentSize = CGSizeMake(scrollWidth+xOffset,110);
//scroll view size show after 125 width the scroll view enabled
[scrollView addSubview:[images objectAtIndex:index]];
// set images on scroll view
xOffset += 170;
}
You can calculate content size width of the scrollview as width = number of images * size of each image. Then set contentSize of the scrollview to this width and the height that you want (scrollView.contentSize = CGSizeMake(width, height))
I've got a TapDetectingImageView class that is pertaining in memory after usage because I do not reuse it in my code.
I change my code now to reuse it instead of re creating a new one each time.
The goal is to configure that TapDetectingImageView object and put it in a view. I'll do it 8 times but with the code below, only the last one is showing. I'm sure I'm missing something, but what? ;)
The view holding the imageViews is potatoeView. I'm adding new TapDetectingImageView through:
[potatoeView addSubview:imageView];
What's wrong in that code?
for (int i = 0; i <= numberOfPotatoes-1; i++)
{
NSLog(#"potatoesView Generation : %d",i);
NSArray *imgArray = [[NSArray alloc] initWithArray:[p objectAtIndex:i]];
UIImage *img1 = (UIImage *) [imgArray objectAtIndex:0];
UIImage *img2 = (UIImage *) [imgArray objectAtIndex:1];
NSString *imgName = (NSString *) [imgArray objectAtIndex:2];
if (imageView == nil) {
imageView = [[TapDetectingImageView alloc] initWithImage:img1 imageHighlighted:img2];
}else {
[imageView setImage:(UIImage *)img1];
[imageView setImageHighlighted:(UIImage *)img2];
}
[imageView setDelegate:self];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = [potatoesSize floatValue] ;
rect.size.width = [potatoesSize floatValue] ;
imageView.frame = rect;
[imageView setName:(NSString *)imgName];
imageView.tag = i+1; // tag our images for later use when we place them in serial fashion
NSValue *val = [potatoesSizeAndPositions objectAtIndex:i];
CGPoint point = [val CGPointValue];
imageView.center = point;
[potatoeView addSubview:imageView];
[imgArray release];
}
You seem to be fundamentally misunderstanding how your views are drawn. When you set up the same view instance with eight different positions and images, it doesn't "stamp" them all out on some canvas as it goes. Its state won't be queried until the main run loop gets around to drawing your view, at which point it'll ask your view for its frame and contents and so on to draw it. If you want to draw eight different images with UIViews, you'll need eight different views.
You only ever create one view, set it as the subview and then change it n-1 times. Drop the if (imageView==nil) and create all 8 of them.
Does anyone idea about how can create UItextivew with Line like so user can easily write text in proper format.
please check this link
https://devforums.apple.com/message/217857#217857
is this possible, i have no idea about this.
Thanks you,
Easiest solution is -
NSInteger distanceBetweenLines = 50; // Distance between each line
NSInteger startMargin = 20; // For any starting margin for our first line
for (int i = 0; i < numberOfLines; i++) {
UIView *lineView = [[UIView alloc] init];
[lineView setFrame:CGRectMake(0, distanceBetweenLines * i + startMargin,
200, 1)];
[lineView setBackgroundColor:[UIColor blackColor]];
[self addSubview:lineView];
[lineView release];
}
This will create multiple UIView lines over your text view. The alternative and perhaps easier way (albeit less flexible) to do it is:
// linesImage is an image with a white background and black lines
UIImageView *linesImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"linesImage"]];
[linesImageView setFrame:CGRectMake(x, y, width, height)];
[self addSubview:linesImageView];
[linesImageView release];
// Just need to maker sure the textview is added to the view after imageview is created to make sure it is on top... or just bring the textview forward in your subviews stack
textview.backgroundColor = [UIColor clearColor]; // So that lines image can be seen through the text view
Apologies if the code doesn't compile, as I haven't tested it in Xcode.
Cheers,
Raal
Dapp - the app design app