2013-04-24 51 views
1

我创建一个自定义的UIButton类,并重写了init方法:加入的UIImageView自定义的UIButton类

- (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)]; 

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

回答

0

A UIButton已经有imageView。你可以简单地使用

self.imageView.image = setaDown 

imageView的其他方面配置为需要(例如位置和大小,以便您的separator拟合)。

+0

我需要两个里面。它的两个不同的图像。 – darkman 2013-04-24 23:26:12

0

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

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

更简单。

+0

问题是图像是相对于textSize,并支持横向和纵向。 – darkman 2013-04-25 13:29:02

0

您可以创建自定义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 
     } 
    } 
}