我使用以下代码更改了UIView的位置,而没有更改视图的大小。
CGRect f = aView.frame;
f.origin.x = 100; // new x
f.origin.y = 200; // new y
aView.frame = f;
是否有更简单的方法仅更改视图位置?
Answers:
aView.center = CGPointMake(150, 150); // set center
要么
aView.frame = CGRectMake( 100, 200, aView.frame.size.width, aView.frame.size.height ); // set new position exactly
要么
aView.frame = CGRectOffset( aView.frame, 10, 10 ); // offset by an amount
编辑:
我还没有编译它,但是它应该可以工作:
#define CGRectSetPos( r, x, y ) CGRectMake( x, y, r.size.width, r.size.height )
aView.frame = CGRectSetPos( aView.frame, 100, 200 );
我有同样的问题。我做了一个简单的UIView类别来解决此问题。
。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
Swift
-请随时使用github.com/katleta3000/UIView-Frame
CGRectOffset
此后已被instance方法代替offsetBy
。
https://developer.apple.com/reference/coregraphics/cgrect/1454841-offsetby
例如,以前是
aView.frame = CGRectOffset(aView.frame, 10, 10)
现在将是
aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10))
aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);
在我的工作中,我们不使用宏。因此,@ TomSwift提供的解决方案启发了我。我看到了CGRectMake的实现,并创建了相同的CGRectSetPos,但没有宏。
CG_INLINE CGRect
CGRectSetPos(CGRect frame, CGFloat x, CGFloat y)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = frame.size.width; rect.size.height = frame.size.height;
return rect;
}
要使用我只放框架X和Y
viewcontroller.view.frame = CGRectSetPos(viewcontroller.view.frame, 100, 100);
为我工作^ _ ^
如果有人需要轻度Swift
延伸以UIView
轻松更改页边距-您可以使用此
view.top = 16
view.right = self.width
view.bottom = self.height
self.height = view.bottom
@TomSwift Swift 3答案
aView.center = CGPoint(x: 150, y: 150); // set center
要么
aView.frame = CGRect(x: 100, y: 200, width: aView.frame.size.width, height: aView.frame.size.height ); // set new position exactly
要么
aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10)) // offset by an amount
这是Swift 3的答案,适用于任何人,因为Swift 3不接受“制作”。
aView.center = CGPoint(x: 200, Y: 200)