Swift:以编程方式更改窗口的背景颜色

时间:2016-05-04 00:26:06

标签: swift cocoa

我试图通过使用具有不同颜色选择的下拉菜单来更改NSViewController中窗口的背景颜色。这是应该进行更改的方法。我究竟做错了什么?任何帮助表示赞赏。

class ViewController: NSViewController, SimplerTextViewDelegate {

    @IBAction func changeBackgroundColor(sender: BackgroundColorPopupButton) {          
        let backgroundColorName= (sender.selectedItem?.title)!
        let backgroundColor = BackgroundColor.GetColor(backgroundColorName)
        self.view.window!.backgroundColor = backgroundColor
    }
}

1 个答案:

答案 0 :(得分:0)

我使用下面的代码来更改背景视图的颜色

@IBAction func Color(_ sender: Any) {

        let alert = UIAlertController(title: "Title", message: "Please Select Background Color", preferredStyle: .actionSheet)

        alert.addAction(UIAlertAction(title: "White", style: .default , handler:{ (UIAlertAction)in

        self.view.backgroundColor = UIColor.white

        }))

        alert.addAction(UIAlertAction(title: "Blue", style: .default , handler:{ (UIAlertAction)in

        self.view.backgroundColor = UIColor.cyan


        }))

        alert.addAction(UIAlertAction(title: "Grey", style: .destructive , handler:{ (UIAlertAction)in

        self.view.backgroundColor = UIColor.lightGray

        }))

        alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler:{ (UIAlertAction)in
            print("User click Dismiss button")
        }))

        self.present(alert, animated: true, completion: {
            print("completion block")
        })

    }