繁体   English   中英

如何将数字或数据从子类 UIView 传递到 UIViewController?

[英]How to pass digit or data from subclassed UIView to UIViewController?

我已经将 UITableViewController 子类化,并且在表格内部我有自定义单元格。 这个自定义单元格在里面有 UIView 的子类。 所以这个 UIView 是写在它自己的类中的。 在我的代码中,UITableViewController 类被命名为 MainViewController.h/.m,UIView 的类被命名为 ContentView.h/.m 所以在 ContentView 中我添加了一个图像和 tapGestureRecognizer。 当图像被点击时,一些日期(在这种情况下是数字)被发送到 MainViewController。 第一个问题是委托方法没有被调用。 如果我用通知中心调用它,它会将其记录为 0.00000 谁能帮我将数据从单元格内的视图传递到 ViewController。

这是我的代码:

内容视图.h:

@class ContentView;
@protocol ContentViewDelegate
- (void)passDigit:(float)someDigit;
@end

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

@interface ContentView : UIView
{
    id <ContentViewDelegate> delegate;
    float someDigit;
}

@property float someDigit;
@property (assign) id <ContentViewDelegate> delegate;

@end

内容视图.m

#import "ContentView.h"


@implementation ContentView
@synthesize someDigit;
@synthesize delegate;

- (void)handleContentTouch:(UIGestureRecognizer *)gesture
{
    someDigit  = 134;
    [self.delegate passDigit:someDigit];
}

- (void)setupView
{
    CGRect frame = self.frame;


    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleContentTouch:)];
    UIImageView *fifthBackground = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)];
    [self addSubview:fifthBackground];
    [fifthBackground setUserInteractionEnabled:YES];
    [fifthBackground addGestureRecognizer:tap];
}

主视图控制器.h

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

@interface MainViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, ContentViewDelegate>
@end

主视图控制器.m

#import "MainViewController.h"

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    ContentView *contentView = [[ContentView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    contentView.delegate = self;
}

- (void) passDigit:(float)someDigit
{
    NSLog(@"%f",someDigit);
}

不确定您正在尝试做什么,可能是您是新手并且正在学习一些东西。 尝试执行以下操作:

更改 mainViewController 中的方法

- (void) showDetailViewControllerWithDigit:(float)someDigit
{
  NSLog(@"%f",someDigit);
}

- (void)passDigit:(float)someDigit
{
  NSLog(@"%f",someDigit);
}

它应该工作。 这里也不是很相关,但您在两个不同的地方拼写了 delegate 和 delegete。 请注意,它们都将被视为两个不同的变量。 虽然没有必要有一个同名的实例变量,但我绝对不会有一个轻微的错字,因为它以后会导致很多问题。

当您为委托定义协议时,您在那里定义的方法应该在委托类中实现。

同样在您的代码中,显然您错过了一些部分,这些部分显示了您在主视图控制器中添加 contentView 的位置。 我假设你有一些

[self.view addSubview:contentView];

在 viewDidLoad 或某些地方,没有它,您甚至无法看到 contentView,因此无法点击它。

快乐编码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM