Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to change the position of UIView?

I change the position of a UIView with following codes without changing size of the view.

CGRect f = aView.frame; f.origin.x = 100; // new x f.origin.y = 200; // new y aView.frame = f; 

Is there more simple way to change only the view position?

like image 554
Seunghoon Avatar asked Mar 01 '11 22:03

Seunghoon


People also ask

What is UIView frame?

Frame A view's frame ( CGRect ) is the position of its rectangle in the superview 's coordinate system. By default it starts at the top left. Bounds A view's bounds ( CGRect ) expresses a view rectangle in its own coordinate system.

What is UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.


2 Answers

aView.center = CGPointMake(150, 150); // set center 

or

aView.frame = CGRectMake( 100, 200, aView.frame.size.width, aView.frame.size.height ); // set new position exactly 

or

aView.frame = CGRectOffset( aView.frame, 10, 10 ); // offset by an amount 

Edit:

I didn't compile this yet, but it should work:

#define CGRectSetPos( r, x, y ) CGRectMake( x, y, r.size.width, r.size.height )  aView.frame = CGRectSetPos( aView.frame, 100, 200 ); 
like image 167
TomSwift Avatar answered Oct 17 '22 07:10

TomSwift


I had the same problem. I made a simple UIView category that fixes that.

.h

#import <UIKit/UIKit.h>   @interface UIView (GCLibrary)  @property (nonatomic, assign) CGFloat height; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y;  @end 

.m

#import "UIView+GCLibrary.h"   @implementation UIView (GCLibrary)  - (CGFloat) height {     return self.frame.size.height; }  - (CGFloat) width {     return self.frame.size.width; }  - (CGFloat) x {     return self.frame.origin.x; }  - (CGFloat) y {     return self.frame.origin.y; }  - (CGFloat) centerY {     return self.center.y; }  - (CGFloat) centerX {     return self.center.x; }  - (void) setHeight:(CGFloat) newHeight {     CGRect frame = self.frame;     frame.size.height = newHeight;     self.frame = frame; }  - (void) setWidth:(CGFloat) newWidth {     CGRect frame = self.frame;     frame.size.width = newWidth;     self.frame = frame; }  - (void) setX:(CGFloat) newX {     CGRect frame = self.frame;     frame.origin.x = newX;     self.frame = frame; }  - (void) setY:(CGFloat) newY {     CGRect frame = self.frame;     frame.origin.y = newY;     self.frame = frame; }  @end 
like image 29
gcamp Avatar answered Oct 17 '22 08:10

gcamp