ios 动态改变视图大小

ios change size of view dynamically

如何在 iOS 中以编程方式更改视图的大小。

我正在 Objective C 中开发一个 iOS 应用程序。

我有几个视图使用以下方法根据特定逻辑隐藏和显示:

-(void)hideGroupStats{
    [groupTimeToFinishForeText setHidden:YES];
    [lblTimeToFinish setHidden:YES];
    [groupTimeToFinishBG setHidden:YES];
} 

在我的视图层次结构中,在它们下面有一个视图,其中包含一张带有 "scale to fit mode" 的地图。 但是,当隐藏其他视图时,它不会调整大小以采用 space.

我是 ios 开发的新手,所以我可能会遗漏一些非常简单的事情。

您必须添加代码来调整视图大小,例如:

mapView.frame = CGRectMake(newX, newY, newWidth, newHeight);

根据 Apple documentation for UIView(请参阅下面的摘录),在调用 setHidden:YES 时,这实际上并没有从它的超级视图中删除视图,它只是让它消失,所以它等效地仍然存在,你可以看到它。有几种方法可以隐藏视图,这样你就可以得到你想要的效果,但我最主要的方法是改变 UIViews 框架(就像 David Ansermots 所说的那样 + 1)

mapView.frame = CGRectMake(newX, newY, newWidth, newHeight); 

newXnewYnewWidthnewHeight 都是您在某处设置的变量,用于确定 UIView 的大小和位置。但是,我会将这条线放在某种动画中,以便为用户提供更好的用户体验,所以我个人会做类似的事情:

- (void)showView:(UIView *)view withAnimationForFrame:(CGRect)frame 
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];

    view.frame = CGRectMake(frame); 

    [UIView commitAnimations];
}

- (void)hideView:(UIView *)view withAnimationForFrame:(CGRect)frame 
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

    view.frame = CGRectMake(frame); 

    [UIView commitAnimations];
}

更改框架大小 and/or 位置应该可以让您想要缩放的其他视图自动按照您的意愿进行缩放。

Extract from Apple Documentation for UIView

Setting the value of this property to YES hides the receiver and setting it to NO shows the receiver. The default value is NO.

A hidden view disappears from its window and does not receive input events. It remains in its superview’s list of subviews, however, and participates in autoresizing as usual. Hiding a view with subviews has the effect of hiding those subviews and any view descendants they might have. This effect is implicit and does not alter the hidden state of the receiver’s descendants.

Hiding the view that is the window’s current first responder causes the view’s next valid key view to become the new first responder.

The value of this property reflects the state of the receiver only and does not account for the state of the receiver’s ancestors in the view hierarchy. Thus this property can be NO but the receiver may still be hidden if an ancestor is hidden.

您可以直接设置视图的框架,例如:-

[你的ViewObject SetFrame :CGRectMake(newX, newY, newWidth, newHeight)];

如果您想将视图的框架设置为依赖于任何其他视图(地图视图),那么您只需使用:-

yourviewObj.frame  = mapview.frame

希望对您有所帮助