gpt4 book ai didi

ios - 添加 addTarget : method to custom UIView

转载 作者:行者123 更新时间:2023-12-01 18:15:42 25 4
gpt4 key购买 nike

我创建了一个类似于 UIStepper 的自定义 UIView,因为我不喜欢 UIStepper 的外观。我希望 UIStepper 有一个个人计数标签,所以我将它添加到我的自定义 View 中并创建了一种增加-减少它的方法。现在我需要一个 [customView addTarget:(id) action:(del) forControlEvents:(UIControlEvents)] 捕获 UIControlEventValueChanged 的​​方法;但我找不到任何关于实现它的信息。我挖掘了 UIButton.h、UIStepper.h 文件,但也没有运气.. 谁能帮我做到这一点?

这是我创建自定义 View 的方式...

CounterView.h

#import <UIKit/UIKit.h>

@interface CounterView : UIView
@property NSString* name;
@property NSInteger count;
@property UILabel *label;
@property NSInteger customTag;

- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag;
@end

CounterView.m
@implementation CounterView

- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag
{
self = [super initWithFrame:CGRectMake(xPoint, yPoint, 24, 52)];
if (self) {
self.customTag = newTag;
self.count = newCount;
self.name = newName;

UIButton *btnUp = [[UIButton alloc] initWithFrame:CGRectMake(3, 2, 18, 12)];
[btnUp setImage:[UIImage imageNamed:@"top.png"] forState:UIControlStateNormal];
[btnUp addTarget:self action:@selector(increaseValue) forControlEvents:UIControlEventTouchUpInside];
UIButton *btnDown = [[UIButton alloc] initWithFrame:CGRectMake(3, 38, 18, 12)];
[btnDown setImage:[UIImage imageNamed:@"bottom.png"] forState:UIControlStateNormal];
[btnDown addTarget:self action:@selector(decreaseValue) forControlEvents:UIControlEventTouchUpInside];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 24, 24)];
[self.label setText:[NSString stringWithFormat:@"%ld", (long)self.count]];
self.label.textAlignment = NSTextAlignmentCenter;

[self addSubview:btnUp];
[self addSubview:btnDown];
[self addSubview:self.label];
}
return self;
}

-(void) increaseValue{
self.count++;
[self.label setText:[NSString stringWithFormat:@"%ld", (long)self.count]];
}
-(void) decreaseValue{
self.count--;
[self.label setText:[NSString stringWithFormat:@"%ld", (long)self.count]];
}
@end

最佳答案

在您实例化 CounterView 的 ViewController 中,添加此

UITapGestureRecognizer *singleFingerTap = 
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleSingleTap:)];
[yourViewInstantiation addGestureRecognizer:singleFingerTap];
[singleFingerTap release];

并且您实现了回调方法:
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
CGPoint location = [recognizer locationInView:[recognizer.view superview]];

//Do stuff here...
}

我希望对你有帮助!

关于ios - 添加 addTarget : method to custom UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22208958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com