2017-05-25 90 views
3

我正在swift 3中创建一个iOS应用程序,我正在创建动态UIView。我需要随机删除自定义视图。随机删除自定义UIView不工作swift 3

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 上面的图片是我的自定义视图

sample output 上面的图片是我的样本输出

当我点击关闭按钮只有一个子视图想要靠近,我选择哪一个。 “在此先感谢”

+0

请问您可以尝试更准确地解释您究竟想要达到什么样的目标以及您有哪些问题? –

+0

获取按钮超级视图并删除该视图 –

+0

您是否试图单击“x”按钮并使用它来解散(移除)浅绿色容器及其所有内容?如果是这样,你能告诉我们当你点击“x”按钮时会发生什么。提供“预期行为”和“实际行为”总是很好,所以我们可以帮助调试和解决问题。 – Hodson

回答

0

有一些方法来实现这一目标,

我建议这一点。

// 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.使 'CustomView' 在你的ViewController对象。

​​

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