如何创建动态按钮iphone X code吗? [英] how to creating dynamic buttons iphone xcode?

查看:98
本文介绍了如何创建动态按钮iphone X code吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要动态地创建uibuttons。所以我对循环用标签创建按钮,并添加到浏览。
所有按钮执行相对于它的标记值同样的动作......但我想更改按钮的属性格式。因此,我需要使用标签值来得到的UIButton ...

我的code ...

 的UIButton *按钮2;
//观点做负载
INT宽度= 30;的for(int i = 1; I< = 5;我++)
{
    按钮2 = [UIButton的buttonWithType:UIButtonTypeCustom];
    [按钮2 addTarget:自我行动:@选择(ratingAction :) forControlEvents:UIControlEventTouchUpInside];
    [按钮2了setBackgroundImage:[UIImage的imageNamed:@star1.png] forState:UIControlStateNormal];
    button2.tag = I;
    button2.backgroundColor =的UIColor clearColor]
    button2.frame = CGRectMake(宽度,78,15,15);    [self.view addSubview:按钮2];    宽度=宽度+30;
} - (无效)ratingAction:(ID *)发件人
{
    //这里使用的标记值我想要得到的按钮,更改背景图片...。
    //例如我想改变的背景标记值1,3,6,7,8 ...
}


解决方案
的UIView

使用 viewWithTag 函数访问你的的UIButton 使用变量值。

查看文档<一个href=\"http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/viewWithTag%3a\"相对=nofollow> viewWithTag

如下使用它。

 的UIButton *则myButton =(UIButton的*)[mySuperView viewWithTag:1];
*的UIButton = myButton的(的UIButton *)[mySuperView viewWithTag:3];
*的UIButton = myButton的(的UIButton *)[mySuperView viewWithTag:6];
.........

I want to create uibuttons dynamically. so i for loop to create button with tag and added to view. all buttons performs the same action with respect to its tag value... but i want to change the propery of the button. Therefore i need to get the uibutton using the tag value...

my code...

UIButton *button2;
//view did load
int width = 30;

for(int i = 1; i <= 5; i++)
{
    button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button2 addTarget:self action:@selector(ratingAction:) forControlEvents:UIControlEventTouchUpInside];
    [button2 setBackgroundImage:[UIImage imageNamed:@"star1.png"] forState:UIControlStateNormal];
    button2.tag = i;
    button2.backgroundColor = [UIColor clearColor];
    button2.frame = CGRectMake(width, 78, 15, 15);

    [self.view addSubview:button2];

    width = width +30;
}

-(void)ratingAction:(id*)sender
{
    // here using the tag value i want to get the button and change the background image….
    // for example i want to change the background for tag values 1,3,6,7 ,8…
}

解决方案

Use viewWithTag function of UIView to access your UIButton using the tag value.

See in Documentation viewWithTag

Use it as below.

UIButton* myButton = (UIButton*)[mySuperView viewWithTag:1];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:3];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:6];
.........

这篇关于如何创建动态按钮iphone X code吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆