我有一个以编程方式创建的UIView子类。我在我的应用程序中使用了纵向和横向模式 自动布局。最初使用initWithFrame设置UIView框架。但是当方向更改为横向时,UIView的CGRect将停留在纵向模式。如何警告UIView子类更改设备方向上的CGRect?
有人可以帮我吗?
这是我最初的UIView框架设置代码:
- (id)initWithFrame:(CGRect)frame videoUrl:(NSURL *)videoUrl{
self = [super initWithFrame:frame];
if (self) {
_frame_width = frame.size.width;
int thumbWidth = ceil(frame.size.width*0.05);
_bgView = [[UIControl alloc] initWithFrame:CGRectMake(thumbWidth-BG_VIEW_BORDERS_SIZE, 0, frame.size.width-(thumbWidth*2)+BG_VIEW_BORDERS_SIZE*2, frame.size.height)];
_bgView.layer.borderColor = [UIColor grayColor].CGColor;
_bgView.layer.borderWidth = BG_VIEW_BORDERS_SIZE;
[self addSubview:_bgView];
答案 0 :(得分:0)
只需检测设备的方向,无论是landscape
还是portrait
模式,然后相应地更改UIView
的大小,请参阅以下代码:
检测设备方向:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation ]== UIDeviceOrientationLandscapeRight)
{
UIView *view = [classObject setupView:xPos yPos:yPos width:widthValue height:heightValue];
yourView.frame = view.frame;
NSLog(@"device orientation Landscapse");
}
if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown )
{
UIView *view = [classObject setupView:xPos yPos:yPos width:widthValue height:heightValue];
yourView.frame = view.frame;
NSLog(@"device orientation portrait");
}
}
在您的课程中编写此方法,无需在任何地方进行调用,以便在用户旋转时检测方向。
在您的课程中创建自定义方法,该方法返回UIView
完整的框架,并在用户更改方向时发送x,y位置及其宽度和高度进行调用,请参阅下面的代码:
-(UIView *) setupView:(float)x yPos:(float)y width:(float)width height:(float) height{
UIView *yourView = [[UIView alloc] initWithFrame:CGRectMake(x,y,width,height)];
yourView.backgroundColor=[UIColor clearColor];
return yourView;
}