Swift 常用控件的创建

1、UILabel

let label:UILabel = UILabel.init(frame: CGRectMake(50, 50, 100, 30))
label.text = "Test"
label.textColor = UIColor.redColor()
label.font = UIFont.systemFontOfSize(20.0)
label.backgroundColor = UIColor.orangeColor()
label.textAlignment = NSTextAlignment.Center;
self.view .addSubview(label)

2、UIButton

func createButton() {
     let button = UIButton(type: UIButtonType.System)
     button.frame = CGRectMake(50, 50, 100, 50)
     button.setTitle("确定", forState: UIControlState.Normal)
     button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
     button.backgroundColor = UIColor.orangeColor()
     button.titleLabel?.font = UIFont.systemFontOfSize(20)
     button.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchUpInside)
     button.layer.cornerRadius = 5.0
     self.view.addSubview(button)
    }

func btnClick(button:UIButton) {
     button.backgroundColor = UIColor.redColor()
    }

3、UITextField

let account:UITextField = UITextField.init(frame: CGRectMake(50, 50, 200, 30))
account.placeholder = "请输入账号"
account.textColor = UIColor.orangeColor()
account.font = UIFont.systemFontOfSize(20)
account.borderStyle = UITextBorderStyle.RoundedRect
self.view .addSubview(account)

4、UIImageView

let imageView:UIImageView = UIImageView(image:UIImage(named:"123"))
imageView.frame = CGRectMake(50, 50, 100, 100)
imageView.backgroundColor = UIColor.orangeColor()
self.view .addSubview(imageView)

5、UITableView

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var datas = ["1","2","3","4"]

    override func viewDidLoad() {
        super.viewDidLoad()

        let tableView:UITableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)

    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier = "CELL"
        let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: identifier)

        cell.textLabel?.text = datas[indexPath.row]
        cell.detailTextLabel?.text = "Test"

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        NSLog("我被点击了%ld",indexPath.row)
    }
}

你可能感兴趣的:(swift,控件)