通过使用UIView,无涯教程可以在屏幕上创建和管理矩形区域,从而可以将UIView定义为对象。无涯教程可以在视图内部拥有任意数量的视图,以创建UIView的层次结构。
通过使用继承UIKit的UIView类中定义的方法和属性来管理UIView。 UIView的声明如下。
class UIView : UIKit
视图是iOS应用程序开发的基础,这就是UIView是对象库中使用最多的对象之一的原因。视图是iOS应用程序的基本构建块,它在其边界矩形内呈现内容,并处理与内容的任何交互。
UIView是iOS应用程序与用户的基础知识和连接点。 iOS应用程序中的视图执行一些活动。
可以通过实例化UIView类以编程方式创建View。无涯教程可以在UIView构造函数中传递框架对象。在iOS应用程序开发中,有许多对象,例如标签,文本字段等,它们直接继承UIView类以使用常见的属性和方法。
let rect = CGRect(x: 10, y: 10, width: 100, height: 100) let myView = UIView(frame: rect)
例1 - 在此示例中,无涯教程将以编程方式创建两个UIViews并同时设置其属性。
ViewController.swift
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //加载视图后进行任何其他设置。 let frame1 = CGRect(x: 100, y: 100, width: 200, height: 200) let myView1 = UIView(frame: frame1) myView1.layer.shadowColor = UIColor.black.cgColor myView1.layer.borderColor = UIColor.black.cgColor myView1.layer.borderWidth = 2 myView1.layer.cornerRadius = 5 myView1.layer.shadowRadius = 2 let frame2 = CGRect(x:100, y:400, width: 200, height: 200) let myView2 = UIView(frame: frame2) myView2.layer.shadowColor = UIColor.blue.cgColor myView2.layer.borderColor = UIColor.blue.cgColor myView2.layer.borderWidth = 2 myView2.layer.cornerRadius = 5 myView2.layer.shadowRadius = 2 myView2.backgroundColor = .green myView1.backgroundColor = .red view.addSubview(myView1) view.addSubview(myView2) } }
例2 - 在此示例中,无涯教程将模拟IOS应用程序上的网页的结构。在此类IOS应用程序中,无涯教程需要显示单独的自定义,无涯教程将在IOS应用程序中使用UIViews。窗口中的左窗格显示了项目中使用的视图和标签的层次结构。
ViewController.swift
在ViewController文件中,无涯教程将添加标签的行为,以便无涯教程可以更改与标签关联的UIView的样式。
链接:https://www.learnfk.comhttps://www.learnfk.com/ios/ios-uiview.html
来源:LearnFk无涯教程网
import UIKit class ViewController: UIViewController { @IBOutlet weak var headerView: UIView! @IBOutlet weak var bodyView: UIView! @IBOutlet weak var footerView: UIView! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var bodyLbl: UILabel! @IBOutlet weak var footerLbl: UILabel! override func viewDidLoad() { super.viewDidLoad() //加载视图后进行任何其他设置。 let headerTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerLblTapped)) headerLbl.isUserInteractionEnabled = true headerLbl.addGestureRecognizer(headerTapGestureRecognizer) let bodyTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(bodyLblTapped)) bodyLbl.isUserInteractionEnabled = true bodyLbl.addGestureRecognizer(bodyTapGestureRecognizer) let footerTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(footerLblTapped)) footerLb l.isUserInteractionEnabled = true footerLbl.addGestureRecognizer(footerTapGestureRecognizer) } @objc func headerLblTapped(){ headerView.backgroundColor = .orange } @objc func bodyLblTapped(){ bodyView.backgroundColor = .green } @objc func footerLblTapped(){ footerView.backgroundColor = .orange } }
输出
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)