我希望UIVIEwController成为该按钮 *** 作的目标.
我该怎么办?
如果它是由Interface Builder创建的,那么使用IBAction很容易.解决方法 如果您以编程方式将按钮添加到UIVIEw的子类,那么您可以通过以下两种方式之一执行此 *** 作:
>您可以使按钮成为视图的属性,然后在实例化视图的vIEwController中,您可以按如下方式设置按钮的目标:
[vIEwSubclass.buttonname addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventtouchUpInsIDe];
这会将按钮的目标设置为vIEwController.m中buttonTapped的方法
>您可以在子视图中创建协议,父视图控件将遵循该协议.在您的视图中,当您添加按钮时,将其设置为在视图中调用方法.然后从该视图中调用委托方法,以便vIEwController可以响应它:
在顶部您的视图子类.h创建协议:
@protocol buttonProtocolname- (voID)buttonWaspressed;@end
为委托创建属性:
@property (nonatomic,assign) ID <buttonProtocolname> delegate;
在子类.m中设置按钮选择器:
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventtouchUpInsIDe];
在buttonTapped:方法中调用委托方法:
- (voID)buttonTapped:(ID)sender { [self.delegate buttonWaspressed];}
在vIEwController.h中,您需要确保它符合协议:
@interface someVIEwController : UIVIEwController <SomebuttonProtocolname>
在初始化子视图时,在vIEwController.m中,您必须设置委托:
SomeVIEw *vIEw = ... // Init your vIEw// Set the delegatevIEw.delegate = self;
最后,将delegate方法buttonWaspressed添加到vIEwController.m:
- (voID)buttonWaspressed { // Put code here for button's intended action.}
更新以提供Swift示例
// Simple delegate protocol.protocol SomeVIEwDelegate: class { // Method used to tell the delegate that the button was pressed in the subvIEw. // You can add parameters here as you like. func buttonWaspressed()}class SomeVIEw: UIVIEw { // define the vIEw's delegate. weak var delegate: SomeVIEwDelegate? // Assuming you already have a button. var button: UIbutton! // Once your vIEw & button has been initialized,configure the button's target. func configurebutton() { // Set your target self.button.addTarget(self,action: #selector(somebuttonpressed(_:)),for: .touchUpInsIDe) } @objc func somebuttonpressed(_ sender: UIbutton) { delegate?.buttonWaspressed() }}// Conform to the delegate protocolclass SomeVIEwController: UIVIEwController,SomeVIEwDelegate { var someVIEw: SomeVIEw! func buttonWaspressed() { // UIVIEwController can handle SomeVIEw's button press. }}
另外,这是一个使用闭包而不是委托的快速示例. (这也可以使用块在ObjC中实现.)
// Use typeAlias to define closuretypealias buttonpressedHandler = () -> VoIDclass SomeVIEw: UIVIEw { // define the vIEw's delegate. var pressedHandler: buttonpressedHandler? // Assuming you already have a button. var button: UIbutton! // Once your vIEw & button has been initialized,for: .touchUpInsIDe) } @objc func somebuttonpressed(_ sender: UIbutton) { pressedHandler?() }}class SomeVIEwController: UIVIEwController { var someVIEw: SomeVIEw! // Set the closure in the VIEwController func configurebuttonHandling() { someVIEw.pressedHandler = { // UIVIEwController can handle SomeVIEw's button press. } }}总结
以上是内存溢出为你收集整理的ios – 如何添加UIViewController作为在以编程方式创建的UIView中创建的UIButton *** 作的目标?全部内容,希望文章能够帮你解决ios – 如何添加UIViewController作为在以编程方式创建的UIView中创建的UIButton *** 作的目标?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)