gpt4 book ai didi

iOS - 带有触摸事件的自定义 View

转载 作者:行者123 更新时间:2023-11-28 20:22:35 34 4
gpt4 key购买 nike

我正在尝试创建一个自定义 UIView,我们称它为 FooView

FooView.h

#import <UIKit/UIKit.h>

@interface FooView : UIView

@property (nonatomic, strong) UITextField *barTextField;
@property (nonatomic, strong) UIButton *submitButton;

@end

FooView.m

#import "FooView.h"

@implementation FooView

@synthesize barTextField = _barTextField;
@synthesize submitButton = _submitButton;

...

@end

FooViewController.h

#import <UIKit/UIKit.h>
#import "FooView.h"

@interface FooViewController : UIViewController

@property (nonatomic, strong) FooView *fooView;

@end

FooViewController.m

#import "SearchViewController.h"

@interface SearchViewController ()
@end

@implementation SearchViewController
@synthesize fooView = _fooView;

@end

我想在FooViewController中实现按钮触摸事件,delegate可以实现吗?如果,怎么做?

目前,我正在以这种方式添加触摸事件

FooViewController.m

- (void)viewDidLoad
{
[self.fooView.submitButton addTarget:self action:@selector(submitTapped:) forControlEvents:UIControlEventTouchUpInside];
}

...
- (IBAction)submitTapped
{
...
}

但我认为这不是一个好的解决方案,因此需要一些专家建议。

有什么想法吗?

最佳答案

是的,你可以使用委托(delegate)来实现

FooView.h

#import <UIKit/UIKit.h>

@protocol FooViewDelegate
-(void)submitButtonClicked:(id)sender;
@end

@interface FooView : UIView

@property (nonatomic, strong) UITextField *barTextField;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, assign) id<FooViewDelegate> delegate;

@end

FooView.m

#import "FooView.h"

@implementation FooView

@synthesize barTextField = _barTextField;
@synthesize submitButton = _submitButton;
@synthesize delegate;
...

-(IBAction)buttonClicked:(id)sender // connect this method with your button
{
[self.delegate submitButtonClicked:sender];
}

@end

FooViewController.h

#import <UIKit/UIKit.h>
#import "FooView.h"

@interface FooViewController : UIViewController <FooViewDelegate>

@property (nonatomic, strong) FooView *fooView;

@end

FooViewController.m

#import "FooViewController.h"

@interface FooViewController ()
@end

@implementation FooViewController
@synthesize fooView = _fooView;

- (void)viewDidLoad
{
_fooView = [[UIView alloc] init];
_fooView.delegate = self;
}

-(void)submitButtonClicked:(id)sender //delegate method implementation
{
NSLog(@"%@",[sender tag]);
}

@end

关于iOS - 带有触摸事件的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15352889/

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