IOS(swift)中用代码创建UI界面

import UIKit


class ViewController: UIViewController{


    var nextY=80

    var labels=[UILabel]()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor=UIColor.whiteColor()

        var addBn=UIButton(frame:CGRect(x:30, y:30, width:60, height:40))

        addBn.setTitle("添加", forState:UIControlState.Normal)

        addBn.setTitleColor(UIColor.blueColor(), forState:UIControlState.Normal)

        addBn.setTitleColor(UIColor.greenColor(), forState:UIControlState.Highlighted)

        addBn.titleLabel?.font=UIFont(name:"Zapfino", size:15)

        addBn.addTarget(self, action:"addButton", forControlEvents:UIControlEvents.TouchUpInside)

        self.view.addSubview(addBn);

        

        var removeBn=UIButton(frame:CGRect(x:230, y:30, width:60, height:40))

        removeBn.setTitle("删除", forState:UIControlState.Normal)

        removeBn.setTitleColor(UIColor.blueColor(), forState:UIControlState.Normal)

        removeBn.setTitleColor(UIColor.greenColor(), forState:UIControlState.Highlighted)

        removeBn.titleLabel?.font=UIFont(name:"Zapfino", size:15)

        removeBn.addTarget(self, action:"deleteButton", forControlEvents:UIControlEvents.TouchUpInside)

        self.view.addSubview(removeBn);

    }

    func addButton(){

        NSLog("addBn");

        var label=UILabel(frame:CGRect(x:80, y:nextY, width:160, height:30))

        label.text="abcd"

        label.font=UIFont(name:"Zapfino", size:15)

        self.labels.append(label)

        self.view.addSubview(label)

        nextY+=50

    }

    func deleteButton(){

        NSLog("deleteBn");

        if(labels.count<=0){

          return

        }

        labels.last?.removeFromSuperview()

        labels.removeLast()

        nextY-=50

        

    }

}

你可能感兴趣的:(iOS)