Swift | iOS开发之Swift入门-UI控件

这篇文章主要写一下swift写基础控件,因为现在大部分能找到的都是2.x版本的,3.0之后语法还是有一些变化的,有些地方会报错。

  • UILabel
var subTitle: UILabel?

  subTitle = UILabel.init(frame: CGRect(x:10,y:10,width:100,height:20))
  subTitle?.font = UIFont.systemFont(ofSize: 15)
  subTitle?.textAlignment = NSTextAlignment.center
  subTitle?.textColor = UIColor.red
  subTitle?.text = "subTitle123456"
  subTitle?.sizeToFit()
  self.addSubview(subTitle!)

var结尾有?表示这是一个option值,不赋值默认为nil。后续使用中表示当值不为空时调用方法。

不加?表示这是一个普通值,必须在初始化时对其进行赋值,否则会报错,因为swift不会自动对变量进行赋值。
var subTitle: UILabel //error
var subTitle: UILabel  = UILabel.init(frame: CGRect(x:10,y:10,width:100,height:20)) //success

!表示确认该值不为空,可以直接调用。

  • UIImageView
var imageView: UIImageView?

  imageView = UIImageView.frame(CGRect(x:5,y:5,width:self.frame.size.width,height:170))
  imageView?.layer.masksToBounds = true
  imageView?.image = UIImage.init(named: "Image")
  • UIButton
 var backBtn: UIButton?

 backBtn = UIButton.init(frame: CGRect(x:0,y:100,width:100,height:20))
 backBtn?.backgroundColor = .red //UIColor可以省略
 backBtn?.setTitle("Back", for: UIControlState.normal)
 backBtn?.addTarget(self, action: #selector(self.goBack(sender:)), for: UIControlEvents.touchUpInside)
 self.view.addSubview(backBtn!)

addTarget中action: #selector(self.goBack(sender:)),以前大多写作action: “goBack:”,但是现在如果这样写会提示Use of string literal for Objective-c selectors is deprecated, use '#selector' instead。

  • UITableView
 let tableView = UITableView(frame:view.bounds, style:UITableViewStyle.plain)
 tableView.register(TableViewCell.self, forCellReuseIdentifier: kCellIdentifier) //注册自定义的cell类型。语法和2.x版本有区别
 tableView.dataSource = self
 tableView.delegate = self
 self.view.addSubview(tableView)

需要在当年VC加入

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

加入UITableViewDataSource,UITableViewDelegate会出现报错the viewcontroller does not conform to protocol uitableviewdatasource。
这个错误只是因为没有实现代理中的方法,只要在当前VC中实现了对应的方法即可。

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
 }
    
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return 90
 }
    
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       // This will be the case for programmatically loaded cells (see viewDidLoad to switch approaches)
       let cell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier, for: indexPath)
       return cell
 }

你可能感兴趣的:(Swift | iOS开发之Swift入门-UI控件)