我正在使用 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 要关闭,我选择了哪个 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/