我正在
swift 3中构建一个iOS应用程序,我正在创建动态UIView.我需要随机删除自定义视图.
上图是我的自定义视图
上面的图片是我的示例输出
class ViewController: UIViewController { var myView: subView! var y : CGFloat! @IBOutlet weak var addButton: UIButton! override func viewDidLoad() { y = 1 super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. } func cancelbutton(_ sender: UIButton) { myView.removeFromSuperview() } @IBAction func buttonAction(_ sender: Any) { y = y + 110 myView = subView(frame: CGRect(x: 80,y: y,width: 300,height: 100)) myView.backgroundColor = UIColor.green myView.actionButton.addTarget(self,action: (#selector(cancelbutton(_:))),for: UIControlEvents.touchUpInside) self.view.addSubview(myView) }
上图是我的自定义视图
上面的图片是我的示例输出
当我点击关闭按钮时,只有一个子视图想要关闭,我选择了哪一个.
“提前致谢”
解决方法
有一些方法可以实现这一目标,
我会建议这个.
// 1
创建一个继承自UIView的新类 – >说’CustomView’.
// 2
在“CustomView”标题中创建“协议”. – >说’CustomViewDelegate’
@protocol CustomViewDelegate @optional - (void)didCloseButtonClickedWithView:(CustomView *)view; @end
并在标题中正确委托.
@property (nonatomic) id <CustomViewDelegate> delegate;
// 3
在CustomView.m中 – >
添加“关闭”按钮的操作. (通过故事板或以编程方式,无论您喜欢什么).
- (void)closeClicked:(UIButton *)button { }
并使用“协议”方法调用委托,
- (void)closeClicked:(UIButton *)button { if (self.delegate && [self.delegate respondsToSelector:@(didCloseButtonClickedWithView:)]) { [self.delegate didCloseButtonClickedWithView:self]; // passing self is 'CustomView' } }
// 4.在ViewController中制作’CustomView’对象.
CustomView *view = [[CustomView alloc] initWithFrame:...]; view.delegate = self; [self.view addSubview:view];
// 5
在ViewController中实现CustomViewDelegate.
- (void)didCloseButtonClickedWithView:(CustomView *)view { // you will get action of close button here // remove your view here. [view removeFromSuperview]; // Additional tips: // Re-arrange frames for other views. }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。