简体   繁体   English

根据服务器的响应动态创建UIButton

[英]Dynamically create UIButton based on response from server

I need to implement a view that require me to create a buttons based on the response from the server. 我需要实现一个视图,该视图要求我根据服务器的响应来创建按钮。

Example response: 响应示例:

{
   ...
    "enable_button_1" = 1;
    "enable_button_2" = 1;
    "enable_button_3" = 1;
   ...
}

Currently, I try to create the buttons manually using Interface Builder. 当前,我尝试使用Interface Builder手动创建按钮。 And each of them are embedded in UIView and put on top of each other. 并且它们每个都嵌入在UIView中并相互叠加。 Like so: 像这样: 一对一创建按钮 They are hidden by default. 它们默认是隐藏的。 So, whenever on or more buttons enabled, I will check using if conditions and then unhide the view. 所以,当上或多个按钮启用,我会检查使用if条件,然后取消隐藏视图。

eg. 例如。 only one button enabled 仅启用一个按钮

一键启用

eg. 例如。 two button enabled 启用两个按钮

启用两个按钮

But the thing is by doing so, I would probably miss a few use case and this seems like a bad practices. 但是这样做的话,我可能会错过一些用例,这似乎是一种不好的做法。 Is there any way that I could create it dynamically instead of creating multiple buttons in UIViews in Interface Builder? 有什么方法可以动态创建它,而不是在Interface Builder中的UIViews中创建多个按钮?

You can always create buttons programatically and add them to your view. 您可以始终以编程方式创建按钮并将其添加到视图中。 You'd have to calculate the width of the button-frame so that they always fit the view 100%. 您必须计算按钮框的宽度,以便它们始终适合视图100%。

For example somehow like this: 例如这样的方式:

    //Here you'd have to calculate the correct position of the button you want to add
    CGRect frame = CGRectMake(0, 0, self.buttonView.frame.size.width, self.buttonView.frame.size.height);
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button setTitle:@"myButton" forState:UIControlStateNormal];
    [self.buttonView addSubview:button];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM