无法在自定义视图中将边框颜色和背景显示为模糊,如Swift中的弹出视图

时间:2018-05-25 11:59:48

标签: ios iphone swift popup xib

我有一些要求将弹出窗口显示为一些自定义选项。

因此,我使用Xib文件将自定义视图作为UIView。

class CustomAlertView : UIView {
@IBOutlet weak var customAlertView : UIView!
@IBOutlet weak var button1 : UIButton!
@IBOutlet weak var button2 : UIButton!

override init(frame: CGRect) { // for using CustomView in code
    super.init(frame: frame)
    self.commonInit()
}

required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
    super.init(coder: aDecoder)
    self.commonInit()
}

private func commonInit() {
    Bundle.main.loadNibNamed("CustomAlertView", owner: self)
    guard let content = customAlertView else { return }
    content.frame = self.bounds
    content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    self.addSubview(content)
}

}

并给出了连接点。

我可以在viewcontroller类中加载视图。

但是,问题是,它没有显示为弹出视图,也没有显示任何边框颜色等,即使我也添加了。

现在的self.view(来自viewcontroller的主视图)仍然移动它有tableview,而我点击自定义视图上的按钮,没有任何事情发生。

   func someAction() {
        self.view.addSubview(customAlert)
        self.customAlert.layer.cornerRadius = 13
        self.customAlert.layer.borderWidth = 10
        self.customAlert.layer.borderColor = UIColor.gray.cgColor
        self.customAlert.clipsToBounds = false
        let radius: CGFloat = self.customAlert.frame.width / 2.0 //change it to .height if you need spread for height

        let shadowPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 2.1 * radius, height: self.customAlert.frame.height))

        self.customAlert.layer.masksToBounds = false
        self.customAlert.layer.cornerRadius = 8; // if you like rounded corners
        self.customAlert.layer.shadowOffset = CGSize(width:-15, height:20);
        self.customAlert.layer.shadowRadius = 5;
        self.customAlert.layer.shadowOpacity = 0.5;
        self.customAlert.layer.shadowPath = shadowPath.cgPath

        self.customAlert.byMonthlyBtn.addTarget(self, action: #selector(button1tapped), for: .touchUpInside)
        self.customAlert.byAnnuallyBtn.addTarget(self, action: #selector(button2tapped), for: .touchUpInside)
}

它看起来像下面的截图

enter image description here

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

private func commonInit() {
    Bundle.main.loadNibNamed("CustomAlertView", owner: self)
    guard let content = customAlertView else { return }
    content.frame = self.bounds
    content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    self.addSubview(content)
}

您的问题是您使用的是加载的 CustomAlertView 。尝试调整您的代码,如下所示。

private func commonInit() {
    guard let view = Bundle.main.loadNibNamed("CustomAlertView", owner: self)?.first as? CustomAlertView else {   
        return
    }
    view.frame = bounds
    view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    addSubview(view)
}