有一定iOS基礎(chǔ)的小伙伴們一定知道确镊,在開發(fā)的過程中UI控件是必不可少的。那么在swift中UI控件都是怎么創(chuàng)建和使用的呢?
UIView
let backView = UIView.init(frame: CGRect(x:100,y:100,width:100,height:100));
backView.backgroundColor = UIColor.green;
self.view.addSubview(backView);UILabel
let label = UILabel.init(frame: CGRect(x:100,y:20,width:100,height:30));
label.text = "Swift";
label.textColor = UIColor.red;
label.textAlignment = NSTextAlignment.center;
label.font = UIFont.systemFont(ofSize: 20);
label.numberOfLines = 0
//文字是否可變填渠,默認值是true
label.isEnabled=true;
//設置陰影顏色和偏移量
label.shadowColor = UIColor.blue
label.shadowOffset = CGSize(width:0.5, height:0.5)
//設置是否高亮和高亮顏色
label.isHighlighted = true
label.highlightedTextColor = UIColor.red
self.view.addSubview(label);-
UIButton
let btn = UIButton.init()
btn.setTitle("ABC", for: UIControlState.normal)
btn.setTitleColor(UIColor.black, for: UIControlState.normal);
btn.setImage(UIImage.init(named: "name"), for: UIControlState.normal);
btn.addTarget(self, action:#selector(btnClick) , for: UIControlEvents.touchUpInside);
self.view.addSubview(btn)func btnClick() { NSLog("被點擊了") }
UIImageView
let imgView = UIImageView.init(frame: CGRect(x:100,y:200,width:100,height:100))
imgView.image = UIImage.init(named: "image");
imgView.backgroundColor = UIColor.yellow;
self.view.addSubview(imgView);UITextField
let textField = UITextField.init(frame: CGRect(x:100,y:300,width:200,height:30))
textField.text = "textField"
textField.placeholder = "xxx"
textField.textColor = UIColor.lightGray
textField.font = UIFont.systemFont(ofSize: 20);
textField.borderStyle = UITextBorderStyle.roundedRect;
self.view.addSubview(textField)-
UITableView
1 ) 定義一個UITableView
var tableView = UITableView();
2 )創(chuàng)建 UITableView
tableView = UITableView.init(frame: CGRect(x:0,y:200,width:self.view.frame.size.width,height:self.view.frame.size.height-200), style: UITableViewStyle.plain);
tableView.delegate = self;
tableView.dataSource = self;
self.view.addSubview(tableView);
3 )遵守UITableViewDelegate,UITableViewDataSource協(xié)議
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource
4 )實現(xiàn)UITableViewDataSource的協(xié)議以及UITableViewDelegate代理方法
//以下方法就不注釋說明了钮惠,相信有iOS基礎(chǔ)的都能夠看得懂。
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "cell"); cell.textLabel?.text = "abc"; return cell; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { NSLog("%d", indexPath.row) }