gpt4 book ai didi

ios - 将 UIImageView 添加到自定义 UIButton 类

转载 作者:行者123 更新时间:2023-11-29 13:14:20 25 4
gpt4 key购买 nike

我创建了一个自定义的 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)];

不知道为什么我会收到这个错误,以及如何解决它。

最佳答案

您可以创建一个自定义的 UIControl,它有 touchUp 事件 并可以在其上放置任何类型的组件。如果 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
}
}
}

关于ios - 将 UIImageView 添加到自定义 UIButton 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com