ios – 随机删除自定义UIView不工作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)

}

《ios – 随机删除自定义UIView不工作swift 3》
上图是我的自定义视图

《ios – 随机删除自定义UIView不工作swift 3》
上面的图片是我的示例输出

当我点击关闭按钮时,只有一个子视图想要关闭,我选择了哪一个.
“提前致谢”

最佳答案 有一些方法可以实现这一目标,

我会建议这个.

// 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.
}
点赞