//这是新建的一个UIView
import UIKit
class SelectView: UIView {
//申明了一个Button变量
var button:UIButton!
//初始化
override init(frame: CGRect) {
super.init(frame: frame)
//设置View的背景颜色和明暗度
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
self.creatButton()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func creatButton(){
var i = 0
//共有四张图片,用for循环循环四次
for(i=0;i<4;i++){
//申明Button的样式
button = UIButton(type: UIButtonType.System)
//确定每个button的位置
let w1 = (self.frame.size.width/4)*CGFloat(i)
let w2 = self.frame.size.width/4/2-35
let w3 = w1 + w2
let y = self.frame.size.height-90
button.frame = CGRectMake(w3, y, 70, 70)
//设置button的背景图片
button.setBackgroundImage(UIImage(named: "\(i+1)"), forState: UIControlState.Normal)
//给button添加点击事件
button.addTarget(self, action: "Selector", forControlEvents: UIControlEvents.TouchUpInside)
button.addSubview(self)
}
}
//这个方法用来点击view空白处时隐藏当前的View
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
UIView.animateWithDuration(0.3) { () -> Void in
self.alpha = 0
}
}
//button的点击事件
func Selector(){
button?.setImage(button?.backgroundImageForState(UIControlState.Normal), forState: UIControlState.Normal)
UIView.animateWithDuration(0.3) { () -> Void in
self.alpha = 0
}
}
}
import UIKit
class ViewController: UIViewController{
//申明一个View
var selectorView1:SelectView?
override func viewDidLoad() {
super.viewDidLoad()
//初始化selectorView1
selectorView1 = SelectView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
//设备刚启动时隐藏selectorView
selectorView1?.alpha = 0
self.view.addSubview(selectorView1!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//点击事件 使selectorView显示出来
@IBAction func selectorButtonClick(sender: UIButton) {
UIView.animateWithDuration(0.3) { () -> Void in
self.selectorView1!.alpha = 1
}
}
}
}
就是上面这样的代码,点击事件发生后,selectorView是显示了,但是四个Button没有显示。
求大神帮忙啊!!!
求大神!
你在creatButton这个方法的末尾写了button.addSubview(self),改成addSubview(button)。