gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:35:53 25 4
gpt4 key购买 nike

我需要实现一个 View ,要求我根据服务器的响应创建一个按钮。

响应示例:

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

目前,我尝试使用 Interface Builder 手动创建按钮。它们中的每一个都嵌入到 UIView 中并放置在彼此之上。就像这样: Creating button one by one它们默认是隐藏的。因此,无论何时启用一个或多个按钮,我都会使用 if 条件进行检查,然后取消隐藏 View 。

例如。仅启用一个按钮

one button enabled

例如。启用两个按钮

two button enabled

但这样做的问题是,我可能会错过一些用例,这似乎是一种不好的做法。有什么方法可以动态创建它,而不是在 Interface Builder 的 UIView 中创建多个按钮?

最佳答案

您始终可以通过编程方式创建按钮并将它们添加到您的 View 中。您必须计算按钮框架的宽度,以便它们始终 100% 适合 View 。

例如像这样:

    //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];

关于ios - 根据服务器的响应动态创建 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26374666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com