ios - 随机删除自定义 UIView Not Working swift 3

标签 ios swift uiview

我正在使用 swift 3 构建一个 iOS 应用程序,我正在其中创建动态 UIView。我需要随机删除自定义 View 。

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

sample output 上图是我的示例输出

当我单击关闭按钮时,只有一个 subview 要关闭,我选择了哪个 subview 。 “提前致谢”

最佳答案

有一些方法可以实现这一点,

我会建议这个。

//1. 创建一个继承自 UIView 的新类 --> Say 'CustomView'。

//2. 在“CustomView” header 中创建“协议(protocol)”。 --> 说'CustomViewDelegate'

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

并在 header 中正确委托(delegate)。

@property (nonatomic) id <CustomViewDelegate> delegate;

//3. 在 CustomView.m 中 --> 为“关闭”按钮添加操作。 (通过 Storyboard 或编程方式,无论您喜欢什么)。

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

}

然后使用“协议(protocol)”方法调用委托(delegate),

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

关于ios - 随机删除自定义 UIView Not Working swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44174956/

相关文章:

objective-c - Xcode Git 与 Google Drive/Dropbox 的问题

iOS 在后台下载图像并更新 UI

ios - 如何在 uicollectionview header 中添加 uicollectionview

xcode - 如何让返回键执行与 Swift 中按下按钮相同的操作?

ios - UIView.convert 在计算 UIWindow 中的 UITableViewCell subview 时给出错误的结果

ios - 将 Interface Builder 中的 UIBarButtonItem 添加到导航的 UIViewController?

带指示器的后台快速发布

ios - 登录后切换 View Controller ......最佳实践

ios - 自定义 UIView 背景图片

ios - 拖动 subview 时防止 UITableViewCell 选择