我正在开发一个应用程序,其中 UI 渲染将取决于服务器发送的 JSON
。
服务器将决定 UI 组件,我实际上已经为 UILabel
、UITextField
等基本组件创建了扩展类,但这似乎是一个非常漫长而复杂的过程。
所以现在我正在寻找能够做到这一点的框架。由于我也将在其他应用程序中实现它,因此它需要是通用的。还有其他方法可以处理它吗?
最佳答案
您可以自己尝试一下,这样在遇到问题时更容易实现和调试。使用任何已构建的框架/库不会为您提供您可能需要的灵活性。
假设您有一个函数可以解析 JSON 并确定它是否是文本字段/按钮/标签/ TextView 等...(它可以是响应中的字段数组中的属性之一)。
创建一个自定义模型类,例如Field
,在该类中,您可以将与要显示在屏幕上的字段相关的所有详细信息;例如 X、Y、宽度、高度、数字、字母数字等等...所有值都需要从 API 获得的 JSON 响应中进行解析。
您可以像下面的函数一样逐一迭代它们:
- (void)setFieldOnScreen:(Field *)f { // Field is a model class that suits your requirement
if (f.type isEqualToString:@"UITextField"]) {
float x = f.x.floatValue;
float y = f.y.floatValue;
float width = f.width.floatValue;
float height = f.height.floatValue;
UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
txtField.delegate = self;
txtField.font = f.font_name; // from repsonse
txtField.tag = f.tag.integerValue; // from response
txtField.textAlignment = f.alignment //NSTextAlignmentLeft or whatever from response
// even you can fill up preset values in it from response
txtField.text = f.presetvalue;
... and so on....
} else if ... /// for UILabel/UIButton/UISwitch or any other subclass of the controls
}
}
关于ios - 根据服务器的响应动态创建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42688315/