2012-11-26 61 views
-3

因此,我一直在努力学习针对iOS的Objective-C编程的基础知识。现在我需要在框架中放置一个简单的按钮以及一个标签。我得到了标签工作,但我不知道按钮代码有什么问题。iOS在viewcontroller.m中添加一个按钮

代码:

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

按钮没有显示出来......

+0

什么问题? – rmaddy

+0

@rmaddy该按钮不会显示...? – user115422

+1

小贴士:如果视图不会出于未知原因,请尝试设置'view.backgroundColor = [UIColor redColor]'。 – DrummerB

回答

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 
} 
+0

生病试试这:)在objective-c中没有任何东西看起来直截了当 – user115422

+2

这与Objective-C无关。这是UIKit框架的一个功能。创建一个按钮需要一定量的设置。 – rmaddy

+0

该方法在页面上的位置?在didviewload部分? – user115422

2

点符号可能会出现问题。使用此设置标题:

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

让我试试这个。 – user115422

+0

不,它仍然没有出现 – user115422

+0

我已经发布了我正在使用的整个代码......我需要做些什么来解决这个问题? – user115422

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]; 
+0

嗯,这是我的代码无论如何... – user115422

+0

对不起,仍然没有工作?即时通讯不知道如何在Objective-C中进行正确调试,这是我第一次使用它。 – user115422

+0

我更新了我的答案 – self

相关问题