1.Swift常用控件创建

时间:2024-02-24 10:10:32

Swift 常用控件的创建

一、基础控件

1.1 UILabel

在 Swift 中,可以使用 UILabel 类来显示文本内容。UILabelUIKit 框架中的一个视图类,用于在界面上显示静态文本。

以下是使用 UILabel 的基本示例:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建一个 UILabel
        let label = UILabel()
        
        // 设置 UILabel 的属性
        label.text = "Hello, Swift!" // 设置文本内容
        label.textColor = UIColor.black // 设置文本颜色
        label.font = UIFont.systemFont(ofSize: 16) // 设置字体和大小
        label.textAlignment = .center // 设置文本对齐方式
        label.numberOfLines = 0 // 设置行数,0表示自动换行
        
        // 设置 UILabel 的位置和大小
        label.frame = CGRect(x: 20, y: 100, width: 200, height: 30)
        
        // 将 UILabel 添加到视图中
        self.view.addSubview(label)
    }
}

在上面的示例中,我们创建了一个 UILabel 对象,并设置了一些常用的属性,如文本内容、颜色、字体、对齐方式和位置大小等。最后,我们将 UILabel 添加到视图中,使其显示在界面上。

除了上述基本属性外,UILabel 还有许多其他属性和方法可供使用,如设置文本的阴影、背景颜色、行间距等。开发者可以根据实际需求来设置 UILabel 的属性,以满足界面设计的要求。

1.2 UIButton

在 Swift 中,可以使用 UIButton 类来创建按钮控件。UIButtonUIKit 框架中的一个视图类,用于在界面上创建可交互的按钮。

以下是使用 UIButton 的基本示例:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建一个 UIButton
        let button = UIButton(type: .system)
        
        // 设置按钮的标题和样式
        button.setTitle("Click Me", for: .normal) // 设置按钮标题
        button.setTitleColor(UIColor.blue, for: .normal) // 设置按钮标题颜色
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16) // 设置按钮标题字体和大小
        
        // 添加按钮点击事件
        button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
        
        // 设置按钮的位置和大小
        button.frame = CGRect(x: 100, y: 200, width: 100, height: 40)
        
        // 将按钮添加到视图中
        self.view.addSubview(button)
    }
    
    @objc func buttonClicked() {
        print("Button clicked!")
    }
}

在上面的示例中,我们创建了一个 UIButton 对象,并设置了一些常用的属性,如按钮标题、标题颜色、标题字体和大小等。通过 addTarget 方法,我们为按钮添加了一个点击事件,当用户点击按钮时,会触发 buttonClicked 方法,并在控制台打印 “Button clicked!”。

除了上述基本属性外,UIButton 还有许多其他属性和方法可供使用,如设置按钮的背景图片、边框样式、点击状态等。开发者可以根据实际需求来设置 UIButton 的属性,以实现不同样式和功能的按钮。

1.3 UITextField

在 Swift 中,可以使用 UITextField 类来创建文本输入框控件。UITextFieldUIKit 框架中的一个视图类,用于在界面上接收用户输入的文本。

以下是使用 UITextField 的基本示例:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建一个 UITextField
        let textField = UITextField()
        
        // 设置文本框的样式和属性
        textField.placeholder = "请输入文本" // 设置占位文本
        textField.textColor = UIColor.black // 设置文本颜色
        textField.font = UIFont.systemFont(ofSize: 16) // 设置字体和大小
        textField.borderStyle = .roundedRect // 设置边框样式
        textField.delegate = self // 设置代理
        
        // 设置文本框的位置和大小
        textField.frame = CGRect(x: 50, y: 100, width: 200, height: 30)
        
        // 将文本框添加到视图中
        self.view.addSubview(textField)
    }
    
    // 实现 UITextFieldDelegate 协议中的方法
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder() // 隐藏键盘
        return true
    }
}

在上面的示例中,我们创建了一个 UITextField 对象,并设置了一些常用的属性,如占位文本、文本颜色、字体、边框样式等。通过设置代理为当前视图控制器,并实现 textFieldShouldReturn 方法,可以在用户点击键盘的 Return 键时隐藏键盘。

除了上述基本属性外,UITextField 还有许多其他属性和方法可供使用,如设置键盘类型、清除按钮样式、输入限制等。开发者可以根据实际需求来设置 UITextField 的属性,以满足不同的输入需求。

1.4 UIImageView

在 Swift 中,可以使用 UIImageView 类来显示图片。UIImageViewUIKit 框架中的一个视图类,用于在界面上显示静态图片或动画图片。

以下是使用 UIImageView 的基本示例:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建一个 UIImageView
        let imageView = UIImageView()
        
        // 设置图片
        imageView.image = UIImage(named: "image_name") // 设置图片的名称
        
        // 设置图片的位置和大小
        imageView.frame = CGRect(x: 50, y: 100, width: 200, height: 200)
        
        // 将图片视图添加到视图中
        self.view.addSubview(imageView)
    }
}

在上面的示例中,我们创建了一个 UIImageView 对象,并通过 UIImage(named: "image_name") 方法设置了要显示的图片。开发者需要将图片资源添加到项目中,并使用图片的名称来加载图片。然后,设置图片视图的位置和大小,并将其添加到视图中即可显示图片。

除了显示静态图片外,UIImageView 还可以用来显示动画图片,实现图片的缩放、旋转等效果。开发者可以根据实际需求来设置 UIImageView 的属性和方法,以实现不同的图片展示效果。

1.5 UITableView

在 Swift 开发中,UITableView 是一个常用的控件,用于显示列表数据。下面是一个简单的示例,演示如何在 Swift 中使用 UITableView:

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var datas = ["1","2","3","4"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let tableView:UITableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier = "CELL"
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: identifier)
        
        cell.textLabel?.text = datas[indexPath.row]
        cell.detailTextLabel?.text = "Test"
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        NSLog("我被点击了%ld",indexPath.row)
    }
}
1.6 UICollectionView

在 Swift 开发中,UICollectionView 是一个非常灵活的控件,用于显示网格布局的数据。下面是一个简单的示例,演示如何在 Swift 中使用 UICollectionView

import UIKit

class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    let data = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.frame = view.bounds
        view.addSubview(collectionView)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.backgroundColor = .blue
        return cell
    }
}

二、其他控件

2.1 UIPageControl

在 Swift 开发中,UIPageControl 是一个用于显示页面指示器的控件,通常用于指示当前页面在滚动视图中的位置。下面是一个简单的示例,演示如何在 Swift 中使用 UIPageControl

(1) 创建一个新的 Swift 文件,命名为 PageControlViewController.swift,并添加以下代码:

import UIKit

class PageControlViewController: UIViewController {
    
    let pageControl = UIPageControl()
    let scrollView = UIScrollView()
    let data = ["Page 1", "Page 2", "Page 3", "Page 4"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        pageControl.numberOfPages = data.count
        pageControl.currentPage = 0
        pageControl.pageIndicatorTintColor = .gray
        pageControl.currentPageIndicatorTintColor = .blue
        pageControl.center = view.center
        view.addSubview(pageControl)
        
        scrollView.isPagingEnabled = true
        scrollView.frame = view.bounds
        scrollView.contentSize = CGSize(width: view.bounds.width * CGFloat(data.count), height: view.bounds.height)
        scrollView.delegate = self
        view.addSubview(scrollView)
        
        for (index, page) in data.enumerated() {
            let label = UILabel(frame: CGRect(x: view.bounds.width * CGFloat(index), y: 100, width: view.bounds.width, height: 50))
            label.text = page
            label.textAlignment = .center
            scrollView.addSubview(label)
        }
    }
}

extension PageControlViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = Int(pageIndex)
    }
}

(2) 在 AppDelegate.swift 文件中,将 PageControlViewController 设置为应用程序的根视图控制器:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = PageControlViewController()
        window?.makeKeyAndVisible()
        return true
    }
}

(3) 运行应用程序,您将看到一个包含页面指示器的滚动视图。

在上面的示例中,我们创建了一个包含页面指示器和滚动视图的 PageControlViewController 类。在滚动视图中,我们添加了几个页面标签,并在滚动时更新页面指示器的当前页面。通过实现 UIScrollViewDelegate 协议中的方法,我们可以根据滚动位置更新页面指示器的当前页面。

开发者可以根据实际需求自定义页面内容和样式,以及处理页面指示器的点击事件等。UIPageControlUIScrollView 是在实现分页效果时常用的组合,可以实现引导页、图片浏览器等功能。

2.2 UIDatePicker

在 Swift 开发中,UIDatePicker 是一个用于选择日期和时间的控件。下面是一个简单的示例,演示如何在 Swift 中使用 UIDatePicker

(1) 创建一个新的 Swift 文件,命名为 DatePickerViewController.swift,并添加以下代码:

import UIKit

class DatePickerViewController: UIViewController {
    
    let datePicker = UIDatePicker()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        datePicker.datePickerMode = .dateAndTime
        datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)
        
        view.addSubview(datePicker)
        
        datePicker.translatesAutoresizingMaskIntoConstraints = false
        datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }
    
    @objc func datePickerValueChanged(_ sender: UIDatePicker) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .short
        
        let selectedDate = dateFormatter.string(from: sender.date)
        print("Selected Date and Time: \(selectedDate)")
    }
}

(2) 在 AppDelegate.swift 文件中,将 DatePickerViewController 设置为应用程序的根视图控制器:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = DatePickerViewController()
        window?.makeKeyAndVisible()
        return true
    }
}

(3) 运行应用程序,您将看到一个包含日期和时间选择器的界面。

在上面的示例中,我们创建了一个包含 UIDatePicker 控件的 DatePickerViewController 类,并设置其 datePickerMode.dateAndTime。我们还添加了一个方法来处理日期选择器值变化的事件,并在控制台打印出所选的日期和时间。

开发者可以根据实际需求自定义日期选择器的样式和模式,以及处理用户选择日期的逻辑。UIDatePicker 是一个常用的控件,用于在应用程序中让用户选择日期和时间,例如在预约、提醒等功能中。

2.3 UIPickerView

在 Swift 开发中,UIPickerView 是一种用于展示选择器的控件,用户可以通过滚动来选择其中的选项。下面是一个简单的示例,演示如何在 Swift 中使用 UIPickerView

(1) 创建一个新的 Swift 文件,命名为 PickerViewController.swift,并添加以下代码:

import UIKit

class PickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    
    let pickerView = UIPickerView()
    let data = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        pickerView.dataSource = self
        pickerView.delegate = self
        
        view.addSubview(pickerView)
        
        pickerView.translatesAutoresizingMaskIntoConstraints = false
        pickerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        pickerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }
    
    // MARK: - UIPickerViewDataSource
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data.count
    }
    
    // MARK: - UIPickerViewDelegate
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return data[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("Selected Option: \(data[row])")
    }
}

(2) 在 AppDelegate.swift 文件中,将 PickerViewController 设置为应用程序的根视图控制器:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: