我正在我的程序中创建一个自定义的UIButton(不是在IB中),我希望它能在不同的状态下显示不同的图像,所以我做了:
UIImage *learnImg=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"01" ofType:@"png"]];
self.learn=[[UIButton buttonWithType:UIButtonTypeCustom] retain];
[self.learn setFrame:CGRectMake(148, 108,254,97)];
[[self.learn imageView] setContentMode:UIViewContentModeScaleAspectFit];
[self.learn setImage:learnImg forState:UIControlStateNormal];
UIImage *learnSelected=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"02" ofType:@"png"]];
[self.learn setImage:learnSelected forState:UIControlEventTouchDown];
[self.learn addTarget:self action:@selector(loadLearn:) forControlEvents:UIControlEventTouchUpInside];
问题是,这两个图像有不同的大小,所以当我点击按钮时,按钮的位置被“翻译”(我相信这是由于'setFrame'行为,因为xy位置应该是相对的)
我想不出办法解决这个问题,我想要的是确保按钮在任何状态下都处于正确位置。无论如何,我可以为每个按钮设置一套完整的样式国家(框架,图像等)?还是其他任何想法?
谢谢!
我终于通过两个动作事件重新设置按钮的中心来解决这个问题:UIControlEventTouchDown和UIControlEventTouchCancel。 感谢所有评论。
答案 0 :(得分:0)
1。)尝试使用setBackgroundImage:forState:
设置背景图像,这样可以根据尺寸拉伸图像。如果您不想这样做,请试用imageEdgeInsets
属性。
2.。)“ontouch”图像所需的状态是UIControlStateHighlighted。如果你想做某事具有“选定”状态(selected
属性)的自定义您需要使用状态的组合(UIControlStateSelected|UIControlStateHighlighted
用于选定的+ ontouch)
答案 1 :(得分:0)
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
[deleteButton setFrame:CGRectMake(285, 5, 30, 30)];
deleteButton.contentMode = UIViewContentModeScaleAspectFill;
UIImage *newImage12 = [UIImage imageNamed:@"x.png"];
deleteButton.tag = indexPath.row;
[deleteButton setImage:newImage12 forState:UIControlStateNormal];
[deleteButton setImage:newImage12 forState:UIControlStateHighlighted];
[deleteButton addTarget:self action:@selector(deleteRemindersMethod:) forControlEvents:UIControlEventTouchUpInside];
根据您的按钮状态提供图像名称。
答案 2 :(得分:0)
UIControlEventTouchDown
不是按钮的状态。它是按钮注册的事件。 UIButton
的各种状态是
enum {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2, // flag usable by app (see below)
UIControlStateApplication = 0x00FF0000, // additional flags available for application use
UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use
};
typedef NSUInteger UIControlState;