当我在界面构建器中创建一个带有背景的自定义 UIButton 时,它会给我这个默认功能,当我在内部进行修饰时,它会把图像涂黑。 如果我以编程方式创建 UIButton,如下所示:
buttonPic = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 100, 63)];
[[buttonPic imageView] setContentMode:UIViewContentModeScaleToFill];
[buttonPic setImage:[video pic] forState:UIControlStateNormal];
它的行为与我在 IB 中创建的完全不同。当我触摸里面时,什么都没有改变。 UIButton 中是否有我缺少的设置? 谢谢
最佳答案
这是以编程方式创建 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];
关于objective-c - UIButton IB 与编程方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763923/