繁体   English   中英

随机删除自定义UIView不起作用swift 3

[英]Remove custom UIView randomly Not Working swift 3

我正在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”标题中输入“ Protocol”。 ->说“ 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.
}

暂无
暂无

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

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