放在UIVisualEffectView顶部的按钮没有响应

时间:2015-04-25 12:48:36

标签: ios iphone uivisualeffectview

我正在尝试向UIVisualEffectView添加一个按钮。但是,我添加的按钮没有响应触摸事件,我不明白为什么。这是代码。

override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "face2")
        let imageView = UIImageView(image: image)
        imageView.frame = CGRectMake(0, 0, 200, 200)
        let button = UIButton(frame: CGRectMake(50, 50, 100, 100))
        button.setTitle("huhuhu", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: .Normal)
        button.userInteractionEnabled = true

        let effect = UIBlurEffect(style: .Light)
        let blurView = UIVisualEffectView(effect: effect)
        blurView.frame = view.bounds

        view.addSubview(imageView)
        view.addSubview(blurView)
        view.addSubview(button)
    }

1 个答案:

答案 0 :(得分:2)

您需要添加目标操作(button.addTarget),即按下时按钮应该执行的操作,请参阅下面修改的代码:

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let image = UIImage(named: "face2")
        let imageView = UIImageView(image: image)
        imageView.frame = CGRectMake(0, 0, 200, 200)
        let button = UIButton(frame: CGRectMake(50, 50, 100, 100))
        button.setTitle("huhuhu", forState: UIControlState.Normal)
        button.addTarget(self, action: "sayHi:", forControlEvents: .TouchUpInside)
        button.setTitleColor(UIColor.blackColor(), forState: .Normal)
        button.userInteractionEnabled = true

        let effect = UIBlurEffect(style: .Light)
        let blurView = UIVisualEffectView(effect: effect)
        blurView.frame = view.bounds

        view.addSubview(imageView)
        view.addSubview(blurView)
        view.addSubview(button)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func sayHi(sender:UIButton) {
        let randomIntH = arc4random_uniform(UInt32(view.bounds.size.width)-40)
        let randomIntV = arc4random_uniform(UInt32(view.bounds.size.height)-15)
        let frame = CGRectMake(CGFloat(randomIntH), CGFloat(randomIntV), 10, 10)
        let label = UILabel(frame: frame)
        label.text = "Hallo"
        label.sizeToFit()
        view.addSubview(label)
    }
}