微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift 简单控件的创建

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.jb51.cc/swift/324043.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐