1

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

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

4

3 回答 3

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
        }
   }
}
于 2018-01-30T05:49:31.503 回答
0

据我所知,您不能向按钮添加 2 张图像。获取一个图像编辑器,将它们合成在一起,然后执行以下操作:

[self setBackgroundImage:[UIImage imageNamed:@"mynewimagename"] forState:UIControlStateNormal]

简单得多。

于 2013-04-24T23:53:50.600 回答
0

AUIButton已经有一个imageView. 你可以简单地使用

self.imageView.image = setaDown

并根据需要配置其他方面imageView(例如,位置和大小,以便separator适合您)。

于 2013-04-24T23:24:00.427 回答