iOS从viewcontroller.m添加一个按钮

时间:2012-11-26 20:25:55

标签: objective-c ios xcode button

所以,我一直在努力学习iOS的Objective-C编程基础知识。现在我需要在框架中放置一个简单的按钮以及标签。我得到了标签,但我不确定按钮代码有什么问题。

代码:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 25, 275, 60)];
label.text = test;//@"I am learning Objective-C for the\n very first time!";
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
//label.lineBreakMode = NSLineBreakByWordWrapping; //iOS 6 only
[self.view addSubview:label];

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(25, 100, 275, 40)];
button.titleLabel.text = @"Hello";
[self.view addSubview:button];

该按钮未显示...

3 个答案:

答案 0 :(得分:3)

创建按钮的典型方法是:

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTitle:@"Hello" forState:UIControlStateNormal];
    btn.frame = CGRectMake(25, 100, 275, 40);
    [btn addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];

然后someMeothod:将是:

- (void)someMethod:(UIButton *)sender {
    // handle button press
}

答案 1 :(得分:2)

点符号可能有问题。使用它来设置标题:

    [button setTitle:@"myTitle" forState:UIControlStateNormal];

答案 2 :(得分:1)

试试这个:

 UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame=CGRectMake(0, 0, 40, 30);
[myButton setTitle:@"normal" forState:UIControlStateNormal];
[myButton setTitle:@"selected" forState:UIControlStateSelected];
myButton.titleLabel.textColor=[UIColor blackColor];
[self.view addSubview:myButton];