Delete custom UIView randomly Doesn't work fast 3

I am creating an iOS app in swift 3 where I am creating a dynamic UIView. I need to delete a custom view in a random way.

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)

}

      

subview above image is my custom view

sample output above image is my output sample

When I click the close button, only one subhead wants to be closed, which is the one I was selected. "Thanks in advance"

+3


source to share


1 answer


There are several ways to achieve this,

I would suggest this.

//1. Create a new class inherited from UIView → Say "CustomView".

// 2. Make "Protocol" in the "CustomView" header. → Say "CustomViewDelegate"

@protocol CustomViewDelegate
@optional
- (void)didCloseButtonClickedWithView:(CustomView *)view;
@end

      

and delegate correctly in the header.

@property (nonatomic) id <CustomViewDelegate> delegate;

      

// 3. in CustomView.m → Add an action for the Close button. (via Storyboard or Programmatically, whichever you prefer).



- (void)closeClicked:(UIButton *)button
{

}

      

And call the delegate using the "Protocol" method,

- (void)closeClicked:(UIButton *)button
{
    if (self.delegate && [self.delegate respondsToSelector:@(didCloseButtonClickedWithView:)])
    {
        [self.delegate didCloseButtonClickedWithView:self]; // passing self is 'CustomView'
    }
}

      

//4. Make CustomView objects in your ViewController.

CustomView *view = [[CustomView alloc] initWithFrame:...];
view.delegate = self;
[self.view addSubview:view];

      

//five. Inject CustomViewDelegate into your ViewController.

- (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.
}

      

0


source







All Articles