xib文件按钮问题

时间:2015-05-02 08:23:08

标签: swift xib uialertcontroller

我有一个xib文件,我已经附加了一个按钮。 xib被加载到故事板上的视图中并且完美地工作。此刻所有按钮都打印到控制台“触摸按钮”。

@IBAction func btnQuickMenuTouchUpInside(sender: UIButton) {

    println("button touched")

}

理想情况下,当我按照以下代码点击按钮时,我想要弹出一个UIAlertController:

    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
   self.presentViewController(alert, animated: true, completion: nil)

然而,它抱怨myMenuVC没有名为presentViewController的成员。

任何人都可以帮助解释我如何通过xib视图中的按钮使UIAlertController工作吗?

非常感谢,艾伦。

PS

myMenuVC.swift的代码如下:

//
//  myMenuVC.swift
//  SwiftLoginScreen
//
//  Created by Alan Tingey on 29/04/2015.
//  Copyright (c) 2015 Alan Tingey. All rights reserved.
//

import UIKit

@IBDesignable class myMenuVC: UIView {

    var view:UIView!
    @IBOutlet var titleLabel: UILabel!

    @IBAction func btnQuickMenuTouchUpInside(sender: UIButton) {

        println("button touched")


        var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
       //self.presentViewController(alert, animated: true, completion: nil)


    }
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        setup()
    }

    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
        setup()
    }

    func setup()
    {
        view = loadViewFromNib()
        view.frame = bounds
        // view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        addSubview(view)
    }

    func loadViewFromNib() -> UIView
    {
        let bundle = NSBundle(forClass:self.dynamicType)
        let nib = UINib(nibName: "vwMyMenuVC", bundle: bundle)
        //let nib = UINib(nibName: "myMenuVC", bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

        var myString:NSString = "straightRED"
        var myMutableString = NSMutableAttributedString()

        myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Zapf Dingbats", size: 28.0)!])

        myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:8,length:3))

        // set label Attribute

        titleLabel.attributedText = myMutableString


        //let view = nib.instantiateWithOwner(self, options: nil)[0] as UIView

        return view
    }

}

1 个答案:

答案 0 :(得分:0)

myMenuVCUIView子类,而不是UIViewController子类。

您可以创建新的视图控制器,并在视图控制器的视图中重新创建此UIView界面。

您还可以直接从myMenuVC UIView子类在应用程序的根视图控制器上显示警报控制器:

UIApplication.sharedApplication().delegate?.window??.rootViewController?.presentViewController(alert, animated: true, completion: nil)