UIButton IB vs以编程方式

时间:2012-03-19 01:24:53

标签: objective-c ios cocoa-touch uibutton

当我在界面构建器中创建具有背景的自定义UIButton时,它为我提供了此默认功能,当我在内部触摸时,它会使图像变黑。 如果我以编程方式创建UIButton,如下所示:

    buttonPic = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 100, 63)];
    [[buttonPic imageView] setContentMode:UIViewContentModeScaleToFill];

[buttonPic setImage:[video pic] forState:UIControlStateNormal];

它的行为与我在IB中创建的行为完全不同。当我在里面触摸时没有任何变化。 我错过了UIButton中的设置吗? 感谢

2 个答案:

答案 0 :(得分:4)

这是以编程方式创建UIButton的方法。

//Specify the type of the button first. No need to use alloc-init for UIButton like other view objects.

UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 

// Give UIButtonTypeRoundedRect to get default Interface builder style button. 

myBtn.frame = CGRectMake(0, 0, 100, 40);
[self.view addSubview:myBtn];

 // Since the button type is custom, give an image to make it visible.
[myBtn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:normal];
[myBtn addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];

// These are some optional methods you may want to use.

myBtn.titleLabel.font = [UIFont fontWithName:@"Arial" size:15];
[myBtn setTitle:@"my button" forState:UIControlStateNormal];
[myBtn setTitleColor:[UIColor blackColor] forState:normal];
[myBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];

答案 1 :(得分:1)

我认为您必须启用以下两个选项之一:

buttonPic.showsTouchWhenHighlighted = YES;
buttonPic.reversesTitleShadowWhenHighlighted = YES;