iPad - 以编程方式将文本设置为按钮

The*_*ter 2 iphone uibutton ipad

所以我是这个iPad业务的新手,我正在基于XML文件的内容以编程方式在scrollview中创建一些按钮.我有这个代码:

float x = (SLIDER_ELEMENT_HEIGHT * i) + 20;
CGRect frame = CGRectMake(x, 0, SLIDER_ELEMENT_WIDTH, SLIDER_ELEMENT_HEIGHT);
UIButton *button = [[UIButton alloc] initWithFrame:frame];

UIColor *bgColor = [[UIColor alloc] initWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
button.backgroundColor = bgColor;

NSString *titleForButton = [NSString stringWithFormat: @"This is my title"];
[button setTitle:titleForButton forState:(UIControlStateNormal | UIControlStateApplication | UIControlStateHighlighted)];

UIColor *fgColor = [[UIColor alloc] initWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
[button setTitleColor:fgColor forState:(UIControlStateNormal | UIControlStateApplication | UIControlStateHighlighted)];

[button addTarget:self action:@selector(buttonMethod:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
[scrl_lastIssues addSubview:button];
Run Code Online (Sandbox Code Playgroud)

现在,我追加的方法监听器工作正常,但按钮的文本从未出现......我做错了什么?

谢谢你的帮助!

ohh*_*hho 5

尝试更改行:

  [button setTitle:titleForButton forState:(UIControlStateNormal | UIControlStateApplication | UIControlStateHighlighted)];
Run Code Online (Sandbox Code Playgroud)

至:

  [button setTitle:titleForButton forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

forState参数不能按照您当前的预期工作,它的工作方式如下:

  [button setTitle:@"Normal" forState:UIControlStateNormal];
  [button setTitle:@"Highlighted" forState:UIControlStateHighlighted];
Run Code Online (Sandbox Code Playgroud)