![](/img/trans.png)
[英]UIControl - addTarget: action: forControlEvents doesn't call the method inside selector
[英]Addtarget for UIControlStateNormal doesn't works
我創建了一個名為SectionButton的自定義UIButton。
該按鈕有2張圖像,一張用於“正常狀態”,另一張用於“選定和突出顯示”狀態。
該按鈕還具有文本,並且當按下按鈕時,必須調整TitleEdgesInset。
在init方法中,添加以下方法:
[self addTarget:self action: @selector(buttonHighlighted:) forControlEvents: UIControlStateHighlighted];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlStateNormal];
但是永遠不會調用方法'buttonNormal:',因此我無法調整titleEdgeInsets屬性。
#import "SectionButton.h"
@implementation SectionButton
- (id)initWithFrame: (CGRect)frame andTitle: (NSString*)title andbaseImageName:(NSString*)imageBaseName
{
if (self = [super initWithFrame: frame])
{
// Create images for button
UIImage* normalImage = [UIImage imageNamed: imageBaseName ];
UIImage* downImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_selected",imageBaseName]];
// Set up button
[self setTitle: [title uppercaseString] forState: UIControlStateNormal]; // Will be used for all states
[self setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
[self.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
[self setBackgroundImage: normalImage forState: UIControlStateNormal];
[self setBackgroundImage: downImage forState: UIControlStateHighlighted];
[self setContentEdgeInsets:UIEdgeInsetsMake(54, 0, 0, 0)];
[self addTarget: self action: @selector(buttonHighlighted:) forControlEvents: UIControlStateHighlighted];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlStateNormal];
}
return self;
}
- (void)buttonHighlighted: (id)sender
{
[self setTitleEdgeInsets:UIEdgeInsetsMake(0,0,-16,0)];
NSLog(@"button selected");
}
- (void) buttonNormal: (id)sender {
[self setTitleEdgeInsets:UIEdgeInsetsMake(0,0,0,0)];
NSLog(@"Button normal");
}
}
@end
您正在傳遞控制狀態來代替ControlEvent,
[self addTarget:self action: @selector(buttonHighlighted:) forControlEvents: UIControlEventTouchDownInside];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];
您只需要對該按鈕調用1個方法。
在這種方法中,您需要根據按鈕的當前狀態執行代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.