Cowboy Tech

iOS-UI-CodeExample

000 使用代码创建UI元素

1
2
3
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
label.text = "Hello jikexueyuan"
view.addSubview(label)

001.使用webView打开网站

需要在info.plist里设置

uiwebview

代码

@IBOutlet weak var wv: UIWebView!
@IBOutlet weak var urlInput: UITextField!
@IBAction func btnGoClicked(sender: AnyObject) {
    wv.loadRequest(NSURLRequest(URL:NSURL(string: urlInput.text!)!))
    urlInput.resignFirstResponder()
}

002.圆形进度指示器

圆形进度指示器

ProgressControl.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import UIKit
class ProgressControl: UIView {
override init(frame:CGRect){
super.init(frame: frame)
self.backgroundColor = UIColor(white: 1, alpha: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var _progressValue:CGFloat = 0
internal func getProgressValue()->CGFloat{
return _progressValue
}
internal func setProgressValue(value:CGFloat){
_progressValue = value
setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor(white: 1, alpha: 0)
// Drawing code
let ctx = UIGraphicsGetCurrentContext()
let r = rect.width/2
CGContextAddArc(ctx, r, r, r, 0, 3.141592653*2, 0)
CGContextSetRGBFillColor(ctx, 0.7, 0.7, 0.7, 1)
CGContextFillPath(ctx)
CGContextAddArc(ctx,r,r,r,0,3.141592653*2*_progressValue, 0)
CGContextAddLineToPoint(ctx, r, r)
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1)
CGContextFillPath(ctx)
}
}

viewController.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import UIKit
class ViewController: UIViewController {
private var pc:ProgressControl!
@IBAction func addProgressBtnPress(sender: AnyObject) {
pc.setProgressValue(pc.getProgressValue()+0.1)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pc = ProgressControl(frame:CGRect(x: 100,
y: 100,
width: 100,
height: 100))
self.view.addSubview(pc)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

003.实时预览自定义控件

1.创建一个new Target

2.创建新的文件MyView.swift在这个target里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import UIKit
@IBDesignable class MyView: UIView {
@IBInspectable var str:String = "Hello"
@IBInspectable var borderWidth:CGFloat = 0{
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor:UIColor = UIColor.clearColor(){
didSet{
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var cornerRaius:CGFloat=0{
didSet{
layer.cornerRadius = cornerRaius
}
}
}

3.实时预览编辑效果

004. 传感器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import UIKit
import CoreMotion
class ViewController: UIViewController {
var cmm:CMMotionManager!
var q:NSOperationQueue!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cmm = CMMotionManager()
q = NSOperationQueue()
}
override func viewWillAppear(animated: Bool) {
startAccelerometerUpdate()
startGyroUpdate()
startListenProximity()
startListenLevel()
}
override func viewWillDisappear(animated: Bool) {
stopAccelerometerUpdate()
stopGyroUpdate()
stopListenProximity()
stopListenLevel()
}
//调用加速度传感器
func startAccelerometerUpdate(){
cmm.accelerometerUpdateInterval = 1
if cmm.accelerometerAvailable && !cmm.accelerometerActive {
cmm.startAccelerometerUpdatesToQueue(q, withHandler: {
(data:CMAccelerometerData?,err:NSError?) -> Void in
print("AccelerometerData:\(data)")
})
}else{
print("加速度传感器不可用")
}
}
//调用陀螺仪
func startGyroUpdate(){
cmm.gyroUpdateInterval = 1
if cmm.gyroAvailable && !cmm.gyroActive{
cmm.startGyroUpdatesToQueue(q, withHandler:{
(data:CMGyroData?,err:NSError?)in
print("Gyro data:\(data)")
})
}
}
//调用距离传感器
func startListenProximity(){
UIDevice.currentDevice().proximityMonitoringEnabled = true
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("proximityChanged"),
name:UIDeviceProximityStateDidChangeNotification,
object: nil)
}
func proximityChanged(){
print("\(UIDevice.currentDevice().proximityState)")
}
//调用电源传感器
func startListenLevel(){
UIDevice.currentDevice().batteryMonitoringEnabled = true
print("\(UIDevice.currentDevice().batteryLevel)")
NSNotificationCenter.defaultCenter().addObserver(self,
selector: ("levelChanged"),
name: UIDeviceBatteryLevelDidChangeNotification,
object: nil)
}
func levelChanged(){
print("\(UIDevice.currentDevice().batteryLevel)")
}
func stopListenLevel(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceBatteryLevelDidChangeNotification,object:nil)
}
func stopAccelerometerUpdate(){
if cmm.accelerometerActive {
cmm.stopAccelerometerUpdates()
}
}
func stopGyroUpdate(){
if cmm.gyroActive{
cmm.stopGyroUpdates()
}
}
func stopListenProximity(){
NSNotificationCenter.defaultCenter().removeObserver(self,name:UIDeviceProximityStateDidChangeNotification,object:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

005. 指南针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import UIKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
@IBOutlet weak var pointerIv: UIImageView!
var lm:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
lm = CLLocationManager()
lm.delegate = self
}
override func viewWillAppear(animated: Bool) {
lm.startUpdatingHeading()
}
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
pointerIv.transform = CGAffineTransformMakeRotation(CGFloat((180-newHeading.magneticHeading)/180.0 * 3.141592653))
}
override func viewWillDisappear(animated: Bool) {
lm.stopUpdatingHeading()
}
}

006.触摸事件的侦听 & 图片的缩小放大

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var iv:UIImageView!
private var lastDistance:CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//开启侦听多点触摸
self.view.multipleTouchEnabled = true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastDistance = 0.0
print("touchedBegan")
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
//输出触摸时某个点的坐标
//print(touches.first!.locationInView(self.view))
//输出有多少个触摸点同时在屏幕上
// print(touches.count)
//输出每一个触摸点的坐标
// for touch in touches {
// print(touch.locationInView(self.view))
// }
//图片的缩小放大
let touchesSet = touches as NSSet
if touchesSet.count == 2{
let p1 = touchesSet.allObjects[0].locationInView(self.view)
let p2 = touchesSet.allObjects[1].locationInView(self.view)
let xx = p1.x - p2.x
let yy = p1.y - p2.y
let currentDistance = sqrt(xx * xx + yy * yy)
if lastDistance == 0.0 {
lastDistance = currentDistance
}else{
if lastDistance - currentDistance > 5{
print("缩小")
lastDistance = currentDistance
iv.transform = CGAffineTransformScale(iv.transform, 0.9, 0.9)
}else if lastDistance - currentDistance < -5{
print("放大")
lastDistance = currentDistance
iv.transform = CGAffineTransformScale(iv.transform, 1.1, 1.1)
}
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("touchedEnded")
}
}

007.浏览器打开网页 - 打电话 - 发短信 - 发邮件

1
2
3
4
5
6
7
8
9
10
11
12
@IBAction func btnGoWeb(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string:"http://www.google.com")!)
}
@IBAction func btnGoMail(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string:"mailto://xxx@jikexueyuan.com")!)
}
@IBAction func btnGoPhone(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string:"tel://10086")!)
}
@IBAction func btnGoMsg(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string:"sms://10086")!)
}

app A调用app B

app A

1
2
3
@IBAction func btnCallIme(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "ime://i.love.you?h=Hello&b=World")!)
}

app B

在info.plist里先注册

register protocol

AppDelegate.swift

1
2
3
4
5
6
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
let vc = LabelViewController(nibName:"LabelViewController",bundle:nil)
window?.addSubview(vc.view)
vc.myLabel.text = "\(url)"
return true
}

008.从相册获取照片

getImage

1
2
3
4
5
6
7
8
9
10
11
12
13
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBOutlet weak var iv:UIImageView!
@IBAction func btnGetImage(sender: AnyObject) {
let c = UIImagePickerController()
c.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
c.delegate = self
self.presentViewController(c, animated:true,completion: nil)
}
func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
iv.image = image
picker.dismissViewControllerAnimated(true, completion: nil)
}