Customized Grid View with Different Items for Odd and Even Indexes - iphone

I have used this custom grid view in my code, and I want to create a grid view which looks like this:
How should I do this in the code? Here's the setup method for items:
- (void)setupItemViews {
for (UIView *view in self.itemViews) {
[view removeFromSuperview];
}
for (UIImageView *image in self.images) {
[image removeFromSuperview];
}
[self.images removeAllObjects];
[self.itemViews removeAllObjects];
// now add the new objects
NSUInteger numItems = [self.menuDelegate menuViewNumberOfItems:self];
for (NSUInteger i = 0; i < numItems; i++) {
GridMenuItemView *itemView = [[GridMenuItemView alloc] init];
GridMenuItem *menuItem = [self.menuDelegate menuView:self itemForIndex:i];
itemView.frame = CGRectMake(0, 0, self.itemSize.width, self.itemSize.height);
itemView.label.text = menuItem.title;
//itemView.imageView.image = menuItem.icon;
itemView.tag = i;
[itemView addTarget:self
action:#selector(itemPressed:)
forControlEvents:UIControlEventTouchUpInside];
[itemView setBackgroundImage:[UIImage imageNamed:menuItem.normalImageName]
forState:UIControlStateNormal];
[itemView setBackgroundImage:[UIImage imageNamed:menuItem.highlightedImageName]
forState:UIControlStateHighlighted];
NSUInteger numColumns = self.bounds.size.width > self.bounds.size.height ? self.columnCountLandscape : self.columnCountPortrait;
[self.itemViews addObject:itemView];
[self addSubview:itemView];
}
Thanks to ctrahey, I got what I wanted. But the method used for setting up the cells is -(void) layoutSubviews as follows:
You can find the corresponding code after this line: **//__n__ ...
- (void)layoutSubviews {
[super layoutSubviews];
//[self removeFromSuperview];
NSUInteger numColumns = self.bounds.size.width > self.bounds.size.height ? self.columnCountLandscape : self.columnCountPortrait;
NSUInteger numItems = [self.menuDelegate menuViewNumberOfItems:self];
if (self.itemViews.count != numItems) {
[self setupItemViews];
}
CGFloat padding = roundf((self.bounds.size.width - (self.itemSize.width * numColumns)) / (numColumns + 1));
NSUInteger numRows = numItems % numColumns == 0 ? (numItems / numColumns) : (numItems / numColumns) + 1;
CGFloat yPadding = 0;
CGFloat totalHeight = ((self.itemSize.height + yPadding) * numRows) + yPadding ;
// get an even y padding if less than the max number of rows
if (totalHeight < self.bounds.size.height) {
CGFloat leftoverHeight = self.bounds.size.height - totalHeight;
CGFloat extraYPadding = roundf(leftoverHeight / (numRows + 1));
yPadding += extraYPadding;
totalHeight = ((self.itemSize.height + yPadding) * numRows) + yPadding;
}
// get an even x padding if we have less than a single row of items
if (numRows == 1 && numItems < numColumns) {
padding = roundf((self.bounds.size.width - (numItems * self.itemSize.width)) / (numItems + 1));
}
for (int i = 0, j = numColumns; i < numItems; i++) {
j--;
if (j<0) {
j += numColumns;
}
//NSUInteger column = j ;
//NSUInteger row = i / numColumns;
UIView *item = [self.itemViews objectAtIndex:i];
//CGFloat xOffset = (column * (self.itemSize.width + padding)) + padding;
//CGFloat yOffset = (row * (self.itemSize.height + yPadding));// + yPadding;
**//__n__ These three lines of code make set the cell items at different xPositions from right and left.
CGFloat xPosition = (i%2) ? 0.0 : self.bounds.size.width - self.itemSize.width;
CGFloat yPosition = i*self.itemSize.height;
item.frame = CGRectMake(xPosition, yPosition, self.itemSize.width, self.itemSize.height);**
//item.frame = CGRectMake(xOffset, yOffset, self.itemSize.width, self.itemSize.height);
// if ((i%numColumns) == 0) {
// UIImageView *img = [self.images objectAtIndex:i/numColumns];
// img.frame = CGRectMake(0, yOffset+76, self.bounds.size.width, 1);
// }//End If
}
//Scroll size.
UIDeviceOrientation currentOrientation = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsPortrait(currentOrientation))
{
self.contentSize = CGSizeMake(self.bounds.size.width, totalHeight + (yPadding * (numRows+1.55)));
}
else if (UIDeviceOrientationIsLandscape(currentOrientation))
{
self.contentSize = CGSizeMake(self.bounds.size.width, totalHeight + (yPadding * (numRows+3)));
}
}

If I understand your intention correctly, the line:
itemView.frame = CGRectMake(0, 0, self.itemSize.width, self.itemSize.height);
Should be using your index i and some simple arithmetic to position the views. One technique I have used in the past is a simple is-odd check using the modulus operator.
CGFloat xPosition = (i%2) ? 0.0 : self.bounds.size.width - self.itemSize.width;
CGFloat yPosition = i*self.itemSize.height;
itemView.frame = CGRectMake(xPosition, yPosition, self.itemSize.width, self.itemSize.height);

just use the uitableview operation.
in that cellforrowatindexpath
set button image and frame based on the odd and even
if(indexpath.orw%2==0)
{
//set your frame here;
}
else
{
// set your frame here;
}

Thanks to ctrahey. The method used for setting up the cells is -(void) layoutSubviews as follows:
You can find the corresponding code after this line: **//__n__ ...
- (void)layoutSubviews {
[super layoutSubviews];
//[self removeFromSuperview];
NSUInteger numColumns = self.bounds.size.width > self.bounds.size.height ? self.columnCountLandscape : self.columnCountPortrait;
NSUInteger numItems = [self.menuDelegate menuViewNumberOfItems:self];
if (self.itemViews.count != numItems) {
[self setupItemViews];
}
CGFloat padding = roundf((self.bounds.size.width - (self.itemSize.width * numColumns)) / (numColumns + 1));
NSUInteger numRows = numItems % numColumns == 0 ? (numItems / numColumns) : (numItems / numColumns) + 1;
CGFloat yPadding = 0;
CGFloat totalHeight = ((self.itemSize.height + yPadding) * numRows) + yPadding ;
// get an even y padding if less than the max number of rows
if (totalHeight < self.bounds.size.height) {
CGFloat leftoverHeight = self.bounds.size.height - totalHeight;
CGFloat extraYPadding = roundf(leftoverHeight / (numRows + 1));
yPadding += extraYPadding;
totalHeight = ((self.itemSize.height + yPadding) * numRows) + yPadding;
}
// get an even x padding if we have less than a single row of items
if (numRows == 1 && numItems < numColumns) {
padding = roundf((self.bounds.size.width - (numItems * self.itemSize.width)) / (numItems + 1));
}
for (int i = 0, j = numColumns; i < numItems; i++) {
j--;
if (j<0) {
j += numColumns;
}
//NSUInteger column = j ;
//NSUInteger row = i / numColumns;
UIView *item = [self.itemViews objectAtIndex:i];
//CGFloat xOffset = (column * (self.itemSize.width + padding)) + padding;
//CGFloat yOffset = (row * (self.itemSize.height + yPadding));// + yPadding;
**//__n__ These three lines of code make set the cell items at different xPositions from right and left.
CGFloat xPosition = (i%2) ? 0.0 : self.bounds.size.width - self.itemSize.width;
CGFloat yPosition = i*self.itemSize.height;
item.frame = CGRectMake(xPosition, yPosition, self.itemSize.width, self.itemSize.height);**
//item.frame = CGRectMake(xOffset, yOffset, self.itemSize.width, self.itemSize.height);
// if ((i%numColumns) == 0) {
// UIImageView *img = [self.images objectAtIndex:i/numColumns];
// img.frame = CGRectMake(0, yOffset+76, self.bounds.size.width, 1);
// }//End If
}
//Scroll size.
UIDeviceOrientation currentOrientation = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsPortrait(currentOrientation))
{
self.contentSize = CGSizeMake(self.bounds.size.width, totalHeight + (yPadding * (numRows+1.55)));
}
else if (UIDeviceOrientationIsLandscape(currentOrientation))
{
self.contentSize = CGSizeMake(self.bounds.size.width, totalHeight + (yPadding * (numRows+3)));
}
}

Related

Resizing a View. Not working the way I planned

I'm resizing a UIView and a UIScrollView based on the number of pixels that UITextViews are being moved. I have all of the pixels being stored in int variables. At the end of my method to populate all of these text views I'm using this:
viewHeight += viewPixelsToBeAdded;
viewHeight -= viewPixelsToBeRemoved;
detailsView.frame = CGRectMake(0, 20, 320, viewHeight);
realDetailsView.frame = CGRectMake(0, 20, 320, viewHeight);
viewHeight is the constant view height which is 1475. I'm using viewPixelsToBeAdded and viewPixelsToBeRemoved to hold the total number of pixels that the view needs to be resized. When I use the above code... my scrollView (detailsView) just stops scrolling. Altogether. I have my objects inside of a view. That view is inside of a scrollView. Is there an easier way to go about resizing this stuff? Why does my scrollView stop scrolling when I increase or decrease its height? Any help would be greatly appreciated. I can post the entire populateLabels method if need be. I kinda feel like I'm taking the long route with it anyway.
-(void) populateLabels {
NSString *noInfo = (#"No Information Available");
lblCgName.text = _Campground.campground;
NSString *cgLoc = _Campground.street1;
NSString *cgCity = _Campground.city;
NSString *cgState = _Campground.state1;
NSString *cgCountry = _Campground.country;
NSString *cgZipPostal = _Campground.zipPostal;
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgCity];
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgState];
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgCountry];
cgLoc = [[cgLoc stringByAppendingString:#" "] stringByAppendingString:cgZipPostal];
lblCgLoc.text = cgLoc;
double dRate = [_Campground.regRate1 doubleValue];
double dRate2 = [_Campground.regRate2 doubleValue];
NSString *rate = [[NSString alloc] initWithFormat:#"$%0.2f",dRate];
NSString *rate2 = [[NSString alloc] initWithFormat:#"$%0.2f",dRate2];
if ([rate2 isEqualToString:#"$0.00"]) {
lblRate.text = rate;
} else {
rate = [[rate stringByAppendingString:#" - "] stringByAppendingString:rate2];
lblRate.text = rate;
}
double dPaRate = [_Campground.paRate1 doubleValue];
double dPaRate2 = [_Campground.paRate2 doubleValue];
NSString *paRate = [[NSString alloc] initWithFormat:#"$%0.2f",dPaRate];
NSString *paRate2 = [[NSString alloc] initWithFormat:#"$%0.2f",dPaRate2];
if ([paRate2 isEqualToString:#"$0.00"]) {
lblPaRate.text = paRate;
} else {
paRate = [[paRate stringByAppendingString:#" - "] stringByAppendingString:paRate2];
lblPaRate.text = paRate;
}
lblLocal1.text = _Campground.localPhone1;
lblLocal2.text = _Campground.localPhone2;
lblTollFree.text = _Campground.tollFree;
lblFax.text = _Campground.fax;
lblEmail.text = _Campground.email;
lblWebsite.text = _Campground.website;
NSString *gps = _Campground.latitude;
NSString *longitude = _Campground.longitude;
gps = [[gps stringByAppendingString:#", "] stringByAppendingString:longitude];
lblGps.text = gps;
int viewHeight = 1475;
int textViewDefaultHeight = 128;
int newTextViewHeight = 0;
int highlightsPixelsRemoved = 0;
int highlightsPixelsAdded = 0;
int notesPixelsRemoved = 0;
int notesPixelsAdded = 0;
int directionsPixelsRemoved = 0;
int directionsPixelsAdded = 0;
int rentalsPixelsRemoved = 0;
int rentalsPixelsAdded = 0;
int viewPixelsToBeRemoved = 0;
int viewPixelsToBeAdded = 0;
//----------------------------------------------------------------------------
txtHighlights.text = _Campground.highlights;
[self fitFrameToContent:txtHighlights];
newTextViewHeight = txtHighlights.contentSize.height;
if (newTextViewHeight > textViewDefaultHeight) {
highlightsPixelsAdded = newTextViewHeight - textViewDefaultHeight;
viewPixelsToBeAdded += highlightsPixelsAdded;
txtTentsHead.frame = CGRectOffset(txtTentsHead.frame, 0, highlightsPixelsAdded);
txtTents.frame = CGRectOffset(txtTents.frame, 0, highlightsPixelsAdded);
txtNotesHead.frame = CGRectOffset(txtNotesHead.frame, 0, highlightsPixelsAdded);
txtNotes.frame = CGRectOffset(txtNotes.frame, 0, highlightsPixelsAdded);
txtDirectionsHead.frame = CGRectOffset(txtDirectionsHead.frame, 0, highlightsPixelsAdded);
txtDirections.frame = CGRectOffset(txtDirections.frame, 0, highlightsPixelsAdded);
txtRentalsHead.frame = CGRectOffset(txtRentalsHead.frame, 0, highlightsPixelsAdded);
txtRentals.frame = CGRectOffset(txtRentals.frame, 0, highlightsPixelsAdded);
} else if (newTextViewHeight < textViewDefaultHeight) {
highlightsPixelsRemoved = textViewDefaultHeight - newTextViewHeight;
viewPixelsToBeRemoved += highlightsPixelsRemoved;
txtTentsHead.frame = CGRectOffset(txtTentsHead.frame, 0, -highlightsPixelsRemoved);
txtTents.frame = CGRectOffset(txtTents.frame, 0, -highlightsPixelsRemoved);
txtNotesHead.frame = CGRectOffset(txtNotesHead.frame, 0, -highlightsPixelsRemoved);
txtNotes.frame = CGRectOffset(txtNotes.frame, 0, -highlightsPixelsRemoved);
txtDirectionsHead.frame = CGRectOffset(txtDirectionsHead.frame, 0, -highlightsPixelsRemoved);
txtDirections.frame = CGRectOffset(txtDirections.frame, 0, -highlightsPixelsRemoved);
txtRentalsHead.frame = CGRectOffset(txtRentalsHead.frame, 0, -highlightsPixelsRemoved);
txtRentals.frame = CGRectOffset(txtRentals.frame, 0, -highlightsPixelsRemoved);
}
//----------------------------------------------------------------------------
txtTents.text = _Campground.tents;
//----------------------------------------------------------------------------
txtNotes.text = _Campground.notes;
[self fitFrameToContent:txtNotes];
newTextViewHeight = txtNotes.contentSize.height;
if (newTextViewHeight > textViewDefaultHeight) {
notesPixelsAdded = newTextViewHeight - textViewDefaultHeight;
viewPixelsToBeAdded += notesPixelsAdded;
txtDirectionsHead.frame = CGRectOffset(txtDirectionsHead.frame, 0, notesPixelsAdded);
txtDirections.frame = CGRectOffset(txtDirections.frame, 0, notesPixelsAdded);
txtRentalsHead.frame = CGRectOffset(txtRentalsHead.frame, 0, notesPixelsAdded);
txtRentals.frame = CGRectOffset(txtRentals.frame, 0, notesPixelsAdded);
} else if (newTextViewHeight < textViewDefaultHeight) {
notesPixelsRemoved = textViewDefaultHeight - newTextViewHeight;
viewPixelsToBeRemoved += notesPixelsRemoved;
txtDirectionsHead.frame = CGRectOffset(txtDirectionsHead.frame, 0, -notesPixelsRemoved);
txtDirections.frame = CGRectOffset(txtDirections.frame, 0, -notesPixelsRemoved);
txtRentalsHead.frame = CGRectOffset(txtRentalsHead.frame, 0, -notesPixelsRemoved);
txtRentals.frame = CGRectOffset(txtRentals.frame, 0, -notesPixelsRemoved);
}
//----------------------------------------------------------------------------
txtDirections.text = _Campground.directions;
[self fitFrameToContent:txtDirections];
newTextViewHeight = txtDirections.contentSize.height;
if (newTextViewHeight > textViewDefaultHeight) {
directionsPixelsAdded = newTextViewHeight - textViewDefaultHeight;
viewPixelsToBeAdded += directionsPixelsAdded;
txtRentalsHead.frame = CGRectOffset(txtRentalsHead.frame, 0, directionsPixelsAdded);
txtRentals.frame = CGRectOffset(txtRentals.frame, 0, directionsPixelsAdded);
} else if (newTextViewHeight < textViewDefaultHeight) {
directionsPixelsRemoved = textViewDefaultHeight - newTextViewHeight;
viewPixelsToBeRemoved += directionsPixelsRemoved;
txtRentalsHead.frame = CGRectOffset(txtRentalsHead.frame, 0, -directionsPixelsRemoved);
txtRentals.frame = CGRectOffset(txtRentals.frame, 0, -directionsPixelsRemoved);
}
//----------------------------------------------------------------------------
txtRentals.text = _Campground.rentals;
[self fitFrameToContent:txtRentals];
newTextViewHeight = txtRentals.contentSize.height;
if (newTextViewHeight > textViewDefaultHeight) {
rentalsPixelsAdded = newTextViewHeight - textViewDefaultHeight;
viewPixelsToBeAdded += rentalsPixelsAdded;
} else if (newTextViewHeight < textViewDefaultHeight) {
rentalsPixelsRemoved = textViewDefaultHeight - newTextViewHeight;
viewPixelsToBeRemoved += rentalsPixelsRemoved;
}
viewHeight += viewPixelsToBeAdded;
viewHeight -= viewPixelsToBeRemoved;
detailsView.frame = CGRectMake(0, 20, 320, viewHeight);
scrollView.frame = CGRectMake(0, 20, 320, viewHeight);
}
It sounds like you're setting the same frame, which is much larger than the screen, on both the UIView and the UIScrollView? So the scroll view doesn't scroll because it's the same size as the view within it — there's nothing extra to show by scrolling.
Probably you want to leave the scroll view frame alone, so that the scroll view takes up the same amount of space on screen regardless of the size of its contents, and set the contentSize property. Similarly I'd expect you to want to pass 0 as the y coordinate for the view within the scrollview since view frames are relative to their parent.
A scrollView has two sizes: Its frame, which determines how large (and where) it is on the screen, and its contentSize, which determines how far it will scroll.
If contentSize is the same or smaller than frame.size, the scrollView will not scroll (because there is nothing to scroll to).
Usually, you'll want to set the contentSize of a scrollView to the size of the view(s) that you put into it.
Say you have a UIImageView that has a size of 1000x1000 points. Its frame will probably by CGRectMake(0, 0, 1000, 1000). Say your ScrollView is a fullscreen on an iPhone in portrait orientation, so it has a frame of CGRectMake(0, 0, 320, 480). If you now set its contentSize to CGSizeMake(1000, 1000), it will be able to scroll over all of the picture. If you make the contentSize a rectangle of 320 x 480, it won't scroll at all. And if you set the contentSize to 2000x2000, you will be able to scroll further than the picture.

How to create grid button on iphone. 10/10 matrix

How to create Grid of Buttons on iphone.
10/10 matrix...
I found NSMatrix for MAC ... Not for iphone...
any alternative way to create grid of button on my view.
#Thanks in advance.
Manually?
int rows = 10;
int cols = 10;
float gridWidth = 320.0;
float gridHeight = 320.0;
float buttonWidth = 28.0;
float buttonHeight = 28.0;
float gapHorizontal = (gridWidth - (buttonWidth * rows)) / (rows + 1);
float gapVertical = (gridHeight - (buttonHeight * cols)) / (cols + 1);
float offsetX;
float offsetY;
int count = 0;
do {
offsetX = gapHorizontal + ((count % rows) * (buttonWidth + gapHorizontal));
offsetY = gapVertical + ((count / rows) * (buttonHeight + gapVertical));
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(offsetX, offsetY, buttonWidth, buttonHeight)];
aView.backgroundColor = [UIColor redColor];
[self.view addSubview:aView];
[aView release];
offsetX+= buttonWidth + gapHorizontal;
count++;
} while(count < rows * cols);
Also check out AQGridView. I guess it's pretty much what you are looking for. And more.
As I usually use this to make grid.. Only you have to just replace with your row and column
#define MatrixRow 3
#define MatrixColumn 3
#define GRID_WIDTH 300
#define GRID_HEIGHT 300
UIView *grid = [[UIView alloc] initWithFrame:CGRectMake(10, 50, GRID_WIDTH, GRID_HEIGHT)];
grid.backgroundColor = [UIColor brownColor];
for (int i = 0; i< (MatrixColumn*MatrixRow); i++) {
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
view.backgroundColor = [UIColor yellowColor];
CGFloat xOrigin = GRID_WIDTH/(MatrixColumn*2) + (GRID_WIDTH/MatrixColumn)*(i%MatrixColumn);
CGFloat yOrigin = GRID_HEIGHT/(MatrixRow*2) + (GRID_HEIGHT/MatrixRow) *(i/MatrixColumn);
NSLog(#" (\"%.2f\" , \"%.2f\")",xOrigin,yOrigin);
view.center = CGPointMake(xOrigin, yOrigin);
[grid addSubview:view];
}
[self.view addSubview:grid];

Animate multiple UIButtons

Hi I am beginner to iOS and I have a question.
I want to re arrange multiple buttons when changing orientations so i have this code to create them :
NSArray *buttonImages = [[NSArray alloc] initWithObjects:#"button_1.png",#"button_2.png",
#"button_3.png", #"button_4.png", nil];
int xcord = 0;
//int ycord = 0;
UIInterfaceOrientation destOrientation = self.interfaceOrientation;
if (destOrientation == UIInterfaceOrientationPortrait || destOrientation == UIInterfaceOrientationPortraitUpsideDown) {
screenWidth = 768;
} else {
screenWidth = 1024;
}
int buttonWidth = 57;
int buttonHeight = 86;
int screenHorizontalDivisions = screenWidth / 5;
for (int i=0; i<4; i++) {
int buttonStartingOffset = screenHorizontalDivisions - buttonWidth / 2;
btn = [[DashButton alloc] initWithFrame:CGRectMake(buttonStartingOffset + xcord, 40, buttonWidth,buttonHeight) andImage:[buttonImages objectAtIndex:i] andTitle:#"Test"];
btn.tag = i+1;
[springboardScrollView addSubview:btn];
//[btn release];
xcord = xcord + screenHorizontalDivisions;
}
and the code to re arrange them is:
- (void)animate: (id)sender {
UIButton *button = (UIButton *)sender;
UIInterfaceOrientation destOrientation = self.interfaceOrientation;
if (destOrientation == UIInterfaceOrientationPortrait || destOrientation == UIInterfaceOrientationPortraitUpsideDown) {
screenWidth = 768;
} else {
screenWidth = 1024;
}
int xcord = 0;
int buttonWidth = 57;
int buttonHeight = 86;
int screenHorizontalDivisions = screenWidth / 5; //find the divisions
int buttonStartingOffset = screenHorizontalDivisions - buttonWidth / 2; //center the button
NSLog (#"%i", button.tag);
switch (button.tag) {
case 1:
button.frame = CGRectMake(buttonStartingOffset, 40, buttonWidth,buttonHeight);
break;
case 2:
button.frame = CGRectMake(buttonStartingOffset + screenHorizontalDivisions, 40, buttonWidth,buttonHeight);
break;
case 3:
button.frame = CGRectMake(buttonStartingOffset + screenHorizontalDivisions * 2, 40, buttonWidth,buttonHeight);
break;
case 4:
button.frame = CGRectMake(buttonStartingOffset + screenHorizontalDivisions * 3, 40, buttonWidth,buttonHeight);
break;
}
then I am calling it when orientation changes:
- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation duration: (NSTimeInterval) duration {
[self animate:btn];
How can I refer to each button one by one?
The code in animate: always return button.tag=4.
Please assist!!
Thanks
Bill.
You need to get the array of UIButtons with the following code:
NSArray* buttons = [springboardScrollView subviews]
This will return all the subviews in the scrollView. If you have UiButtons only that will be all buttons in the scroll view. If you have other types of views in scroll view then you need to iterate through array and check if the object is UiButton, which is explained on the following link .
Then you can change the frame, image, position....

How to move a label with the wave of the iPhone?

The code below is from the book Beginning iPhone 3 Development, chapter 15, using the accelerometer to control a ball.
I want to use a label instead of the ball, and only move in the x direction.
However, I donno how to revise the code to achieve this goal.
Can anyone please help me?
THX so much!!!!
- (id)initWithCoder:(NSCoder *)coder {
if (self = [super initWithCoder:coder]) {
self.image = [UIImage imageNamed:#"ball.png"];
self.currentPoint = CGPointMake((self.bounds.size.width / 2.0f) +
(image.size.width / 2.0f),
(self.bounds.size.height / 2.0f) + (image.size.height / 2.0f));
ballXVelocity = 0.0f;
ballYVelocity = 0.0f;
}
return self;
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
[image drawAtPoint:currentPoint];
}
- (void)dealloc {
[image release];
[acceleration release];
[super dealloc];
}
//#pragma mark -
- (CGPoint)currentPoint {
return currentPoint;
}
- (void)setCurrentPoint:(CGPoint)newPoint {
previousPoint = currentPoint;
currentPoint = newPoint;
if (currentPoint.x < 0) {
currentPoint.x = 0;
//ballXVelocity = 0;
ballXVelocity = - (ballXVelocity / 2.0);
}
if (currentPoint.y < 0){
currentPoint.y = 0;
//ballYVelocity = 0;
ballYVelocity = - (ballYVelocity / 2.0);
}
if (currentPoint.x > self.bounds.size.width - image.size.width) {
currentPoint.x = self.bounds.size.width - image.size.width;
//ballXVelocity = 0;
ballXVelocity = - (ballXVelocity / 2.0);
}
if (currentPoint.y > self.bounds.size.height - image.size.height) {
currentPoint.y = self.bounds.size.height - image.size.height;
//ballYVelocity = 0;
ballYVelocity = - (ballYVelocity / 2.0);
}
CGRect currentImageRect = CGRectMake(currentPoint.x, currentPoint.y,
currentPoint.x + image.size.width,
currentPoint.y + image.size.height);
CGRect previousImageRect = CGRectMake(previousPoint.x, previousPoint.y,
previousPoint.x + image.size.width,
currentPoint.y + image.size.width);
[self setNeedsDisplayInRect:CGRectUnion(currentImageRect,
previousImageRect)];
}
- (void)draw {
static NSDate *lastDrawTime;
if (lastDrawTime != nil) {
NSTimeInterval secondsSinceLastDraw =
-([lastDrawTime timeIntervalSinceNow]);
ballYVelocity = ballYVelocity + -(acceleration.y *
secondsSinceLastDraw);
ballXVelocity = ballXVelocity + acceleration.x *
secondsSinceLastDraw;
CGFloat xAcceleration = secondsSinceLastDraw * ballXVelocity * 500;
CGFloat yAcceleration = secondsSinceLastDraw * ballYVelocity * 500;
self.currentPoint = CGPointMake(self.currentPoint.x + xAcceleration,
self.currentPoint.y +yAcceleration);
}
// Update last time with current time
[lastDrawTime release];
lastDrawTime = [[NSDate alloc] init];
}
To start, you create the label as a property of the controller. If you use IB then make it an IBOutlet and hook it up. Then in the code above, where it uses the ball image, substitute the label. Of course, you don't have to draw the label it will handle that itself.
The movement logic is exactly the same except you move the center or origin of the label instead of drawing the ball in a rect.
Edit
thank u! But I am not quite understand
how to move the center of the label?
Like this:
self.myLabel.center=CGPointMake(newX,newY);
You can also animate the change so that the label appears to move smoothly. See the UIView class docs for the methods.

UIScrollView offsetting content double the requested amount

The Issue
My PSWSnapshotView's end up exactly snapshotIndex too far to the right inside the _scrollView (40px offset). Yet, they are set with their frame to have the first one at (0, 0), though that first one shows up at (snapshotInset, 0) instead :/.
The Code
- (void)layoutViews
{
CGRect frame = self.frame;
CGFloat pageWidth = frame.size.width - (snapshotInset * 2);
CGRect pageFrame = CGRectMake(0.0f, 0.0f, pageWidth, frame.size.height);
NSInteger pageCount = [applications count];
[pageControl setNumberOfPages:pageCount];
[scrollView setFrame:CGRectMake(snapshotInset, 0.0f, pageWidth, frame.size.height)];
[scrollView setContentSize:CGSizeMake((pageWidth * pageCount) + 1.0f, frame.size.height)];
for (int i = 0; i < pageCount; i++) {
PSWSnapshotView *view;
if ([snapshotViews count] <= i)
{
PSWSnapshotView *view = [[PSWSnapshotView alloc] initWithFrame:pageFrame application:[applications objectAtIndex:i]];
view.delegate = self;
[scrollView addSubview:view];
[snapshotViews addObject:view];
[view release];
}
else
{
view = [snapshotViews objectAtIndex:i];
[view setFrame:pageFrame];
}
pageFrame.origin.x += pageWidth;
}
}
The Values
self.frame.size.width = 320;
self.frame.size.height = 370;
snapshotInset = 40;
[applications count] = 2;
All the sizes and frames are set correctly (I checked w/ NSLog).
Are you possibly setting the scrollView.contentOffset somewhere, independent of this? Also, and this may just be a copy/paste issue, you reference both snapshotInset and _snapshotInset.