我创建了一个自定义UIButton类并覆盖了init方法:
- (id)initWithFrame:(CGRect)frame title:(NSString *)titulo
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
setaDown = [UIImage imageNamed:@"setaDown"];
separator = [UIImage imageNamed:@"separatorLine"];
self = [UIButton buttonWithType:UIButtonTypeCustom];
[self setFrame:frame];
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
self.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
seta = [[UIImageView alloc]initWithFrame:CGRectMake(frame.size.width-setaDown.size.width*2, frame.size.height/2, setaDown.size.width/1.2, setaDown.size.height/1.2)];
[seta setImage:setaDown];
[self addSubview:seta];
separatorLine = [[UIImageView alloc]initWithFrame:CGRectMake(5, frame.size.height-2, frame.size.width-10, separator.size.height)];
[separatorLine setImage:separator];
[self addSubview:separatorLine];
[self setTitle:titulo forState:UIControlStateNormal];
[self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
self.backgroundColor = [UIColor whiteColor];
}
return self;
}
问题是,图片没有显示在按钮中,我在行中有exc_bad_access
:
seta = [[UIImageView alloc]initWithFrame:CGRectMake(frame.size.width-setaDown.size.width*2, frame.size.height/2, setaDown.size.width/1.2, setaDown.size.height/1.2)];
不知道为什么我会得到这个错误,以及如何解决它。
答案 0 :(得分:1)
您可以创建自定义UIControl
,它有touchUp event
并在其上放置任何类型的组件。如果UIButton
无法满足您的需求,那么您可以自定义UIControl
。
例如:
class MyButton: UIControl {
@IBOutlet var myImage: UIImageView!
@IBOutlet var myTitle: UILabel!
@IBOutlet var myImage2: UIImageView!
override var isSelected: Bool {
didSet {
// Configure image for `isSelected` status been changed.
myImage.image = (isSelected ? selImg : normalImg)
}
}
override var isEnabled: Bool {
didSet {
// Configure for `isEnabled` status been changed.
myTitle.isEnabled = isEnabled
}
}
}
答案 1 :(得分:0)
UIButton
已有imageView
。你可以简单地使用
self.imageView.image = setaDown
并根据需要配置imageView
的其他方面(例如,位置和大小,以便separator
适合)。
答案 2 :(得分:0)
据我所知,您无法在按钮上添加2张图像。获取图像编辑器,将它们组合在一起然后执行此操作:
[self setBackgroundImage:[UIImage imageNamed:@"mynewimagename"] forState:UIControlStateNormal]
更简单。