iphone - 制作通用 View Controller

标签 iphone ipad ios uiview uiviewcontroller

我正在开发一个通用的 iOS 应用程序。

我想要的是让我的所有 View 根据屏幕大小自动调整大小,我的意思是我不想硬编码任何 CGRect 大小或使用 Interface Builder;我使用的是一个特定的应用程序示例,但我非常感谢能在许多类似场景中使用的答案。

这是一个非常简单的应用程序,但我希望答案可以告诉我如何为我的所有 View 执行此操作,以便它们可以调整为任何大小。

对于这个特定的应用程序,我正在构建如下所示的内容:

A simple mockup of a screen used in my app.

这是一个特别棘手的例子,因为 MKMapView 必须用框架初始化,但我希望你能帮助我。

我遇到的第一个问题是在我的 loadView 方法中:

MKMapView *mapView=[[MKMapView alloc ] initWithFrame:CGRectZero];

    mapView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

    self.view=mapView;

除非 View Controller 由 UINavigationController 管理,否则自动调整掩码不起作用;我不知道为什么。

下一个问题是当我想在屏幕底部添加我的 UIToolbar 时。

为了得到这个,我做了以下事情:

UIToolbar *toolBar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 420, 320, 40)];

toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;

[self.view addSubview:toolBar];

这适用于 iPhone,但不适用于 iPad(工具栏的宽度已调整,但显然屏幕底部没有记录器),因为尺寸是硬编码的。

很抱歉提出这么长的问题,但我认为这些答案对我和其他有需要的开发者来说是一个很好的资源。

如果我不清楚,请告诉我。

最佳答案

CGGeometry中定义的一些函数在处理 iOS View 几何时非常有用。

假设您想要将整个帧分成两部分。底部应该是位于屏幕底部的工具栏框架,高度为 44 像素。顶部的剩余部分应该全部给 map 。执行此操作的一个有用函数是 CGRectDivide,它定义为:

void CGRectDivide (
   CGRect rect,
   CGRect *slice,
   CGRect *remainder,
   CGFloat amount,
   CGRectEdge edge
);

您将完整的 CGRect 传递给它,两个未初始化的 CGRect 将在分割后填充正确的帧大小、开始的边缘(左、右、上、下),以及与该边缘的距离。

玩弄unicode艺术,这是我能做的最好的了。完整的矩形分为两部分。底部的黑线是工具栏的框架。白色矩形是 map 获得的框架。

▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫▫
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];

CGRect mapFrame, toolbarFrame;
CGRectDivide(appFrame, &toolbarFrame, &mapFrame, 44, CGRectMaxYEdge);

// map is an MKMapView
map.frame = mapFrame;
// toolbar is a UIToolbar
toolbar.frame = toolbarFrame;

这是它在 iPhone 和 iPad 模拟器上的样子。

enter image description here enter image description here

关于iphone - 制作通用 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5023535/

相关文章:

objective-c - 如何将 Storyboard连接到 .h 和 .m

ios - Swift 3循环到图像的中心像素

iphone - SenTesting 在第一次 STAsert 失败后停止测试

ios - iPad OpenGL ES 应用程序的大部分不是视网膜

iPhone 开发 : Get images from RSS feed

iphone - 保存和加载数据 - CoreData

ios - 从 nsdictionary 获取一个值

ios - 在 GMSMapView 导出中显示 map 的问题

ios - 在不减慢 UI 的情况下在 UITableViewCell 中显示 MKMapView

iphone - three20 和 iOS 6 不工作