[英]What's the correct way to add a UIImageView or UITextView to a custom UIButton class?
[英]Add UIImageView to custom UIButton class
我創建了一個自定義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 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
}
}
}
一個UIButton
已經有一個imageView
。 您可以簡單地使用
self.imageView.image = setaDown
並根據需要配置imageView
其他方面(例如,位置和大小,以便separator
適合)。
據我所知,您不能在一個按鈕上添加2張圖像。 獲取圖像編輯器,將它們組合在一起,然后執行以下操作:
[self setBackgroundImage:[UIImage imageNamed:@"mynewimagename"] forState:UIControlStateNormal]
簡單得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.