objective-c - UIButton IB 与编程方式

标签 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 中是否有我缺少的设置? 谢谢

最佳答案

这是以编程方式创建 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/

相关文章:

ios - 完全删除 UIBezierPath 和 CAShapeLayer 绘制的项目

objective-c - 不可编辑的 NSTextfield,以使其在字符串太长时自动调整大小,例如英语单词到法语

ios - 定时器 3 :30 mins which has a options with add and skip?

ios - 当 "Button Shapes"辅助功能打开时,UIBarButton 标题文本未显示在模态视图 Controller 上

objective-c - Objective-C 自动释放问题,代码有什么问题?

ios - Instagram iOS Hook 与非方形图像

ios - 从 Xcode 4.2 升级到 Xcode 5 时,ARC 似乎无法正常工作

iphone - IOS:如何为缩进级别的变化设置动画?

objective-c - 如何更改TapkuLibrary日历对象上的事件标记

iphone - 苹果陀螺仪示例代码