Ios 如何将按钮操作从uiview传递到另一个view控制器
我有一个名为leftMenuView的uiview,在该视图上有一个按钮,我想向该按钮添加一个动作,这样动作方法应该调用一个视图控制器。看看我做了什么: 这是我的左菜单视图Ios 如何将按钮操作从uiview传递到另一个view控制器,ios,objective-c,uiview,Ios,Objective C,Uiview,我有一个名为leftMenuView的uiview,在该视图上有一个按钮,我想向该按钮添加一个动作,这样动作方法应该调用一个视图控制器。看看我做了什么: 这是我的左菜单视图 #import <UIKit/UIKit.h> @class LeftMenuView; @protocol LeftMenuViewProtocol <NSObject> -(void)homeClicked; @end @interface LeftMenuView : UIView
#import <UIKit/UIKit.h>
@class LeftMenuView;
@protocol LeftMenuViewProtocol <NSObject>
-(void)homeClicked;
@end
@interface LeftMenuView : UIView
@property (nonatomic,assign) id<LeftMenuViewProtocol> customDelegate;
-(IBAction)homeClickedAction:(id)sender;
@end
现在我试图通过委托调用该方法
现在在homeViewController.h中
@interface homeViewController : UIViewController<LeftMenuViewProtocol>
但是上面的方法并没有像在leftViewMenu.m中那样被调用。希望有人能帮助我解决这个问题。我想在homeViewController中,您有一个LeftMenuView属性,需要将customDelegate设置为self。在homeViewController viewDidLoad方法中:
或者,假设您的homeViewController中的leftMenuView上有一个引用,您可以通过编程方式创建UIButton,并使用homeViewController设置按钮的目标。例如,在homeViewController的viewDidLoad中,可以执行以下操作:
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 20)]; // set the frame you want
myButton.backgroundColor = [UIColor redColor]; // Do additional set up
[myButton addTarget:self action:@selector(homeClicked) forControlEvents:UIControlEventTouchUpInside]; // here the target of your button's action is your homeViewController
[self.leftMenuView addSubView:myButton]; // Add the button in your left view
您是否将customDelegate设置为leftView.customDelegate=self;在homeViewController的viewDidload中?我无法想象您是如何将iAction按钮与view类连接起来的。是的,正如Bonafons上面所说,您没有提到是否已将homeViewController设置为leftViewMenu类的委托。您刚才提到homeViewController正在确认LeftMenuViewProtocoli是否编写了leftView.customDelegate=self;但仍然没有进展。答案简单但非常有效。
-(void)homeClicked
{
NSLog(@"Clicked Home");
}
self.leftMenuView.customDelegate = self;
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 20)]; // set the frame you want
myButton.backgroundColor = [UIColor redColor]; // Do additional set up
[myButton addTarget:self action:@selector(homeClicked) forControlEvents:UIControlEventTouchUpInside]; // here the target of your button's action is your homeViewController
[self.leftMenuView addSubView:myButton]; // Add the button in your left view