1,UILabel
刚刚接触swift,代码量不够,文档已经看过了,但是发现写起来还是挺生疏的。从基础练习一下,代码如下:
let label:UILabel = UILabel.init(frame:CGRectMake(100,100,30))
label.text = "Hi I'm Jack"
label.textColor = UIColor.blackColor()
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.yellowColor()
self.view.addSubview(label)
运行结果如下:
2,UIbutton
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
let button: UIButton = UIButton.init(type: .System) button.frame = CGRectMake(0,80,30) button.center = self.view.center
// button.setTitleColor(UIColor.blackColor(),forState: .Normal)
button.setTitle(“button1”,forState: .Normal)
button.addTarget(self,action:”buttonClicked:”,forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button) } func buttonClicked(button: UIButton){ NSLog("%@ is clicked",button.titleLabel!.text!) }
运行结果:
3,UIImageView
let imageview1 = UIImageView.init(frame: CGRectMake(100,100))
imageview1.image = UIImage.init(named: "picture1")
self.view .addSubview(imageview1)
运行结果:
4,UITableView
//
// ViewController.swift
// swiftDemo
//
// Created by Jack on 16/4/6.
// Copyright © 2016年 Jack. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var tableView:UITableView?
let items = ["武汉","上海","北京","深圳","广州","重庆","香港","台海","天津"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
self.tableView = UITableView.init(frame: self.view.frame)
self.tableView!.dataSource = self
self.tableView!.delegate = self
self.tableView!.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell1")
self.view.addSubview(self.tableView!)
}
func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell1")!
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
NSLog("cell Title %@",items[indexPath.row])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
原文链接:https://www.f2er.com/swift/324043.html