TableView 使用

1. 基本使用

1.1 创建 TableView

let tableView = UITableView(frame: view.bounds, style: .plain)

// 设置数据源和代理
tableView.dataSource = self
tableView.delegate = self

// 注册 cell
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

view.addSubview(tableView)

1.2 实现数据源方法


// 返回行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

// 返回 cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "第 \(indexPath.row) 行"
    return cell
}

1.3 实现代理方法

// 选中某一行
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("选中了第 \(indexPath.row) 行")
}


// 取消选中某一行
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    print("取消选中了第 \(indexPath.row) 行")
}

// 返回行高
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50
}

// 返回头部视图
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 50))
    headerView.backgroundColor = .red
    return headerView
}

// 返回头部高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50
}

// 返回尾部视图
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 50))
    footerView.backgroundColor = .blue
    return footerView
}

// 返回尾部高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 50
}

2. 自定义 Cell

2.1 创建 Cell

class CustomCell: UITableViewCell {

    var titleLabel: UILabel!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
        titleLabel.textColor = .black
        titleLabel.textAlignment = .center
        contentView.addSubview(titleLabel)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

2.2 注册 Cell

tableView.register(CustomCell.self, forCellReuseIdentifier: "customCell")

2.3 使用 Cell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
    cell.titleLabel.text = "第 \(indexPath.row) 行"
    return cell
}

3. 自定义 HeaderView 和 FooterView

3.1 创建 HeaderView 和 FooterView

class CustomHeaderView: UIView {

    var titleLabel: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)

        titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
        titleLabel.textColor = .black
        titleLabel.textAlignment = .center
        addSubview(titleLabel)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

3.2 使用 HeaderView 和 FooterView

// 返回头部视图
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = CustomHeaderView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 50))
    headerView.titleLabel.text = "第 \(section) 组"
    return headerView
}

// 返回尾部视图
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = CustomHeaderView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 50))
    footerView.titleLabel.text = "第 \(section) 组"
    return footerView
}

4. 自定义 SectionHeader 和 SectionFooter

4.1 创建 SectionHeader 和 SectionFooter

class CustomSectionHeader: UITableViewHeaderFooterView {

    var titleLabel: UILabel!

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)

        titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
        titleLabel.textColor = .black
        titleLabel.textAlignment = .center
        contentView.addSubview(titleLabel)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

4.2 注册 SectionHeader 和 SectionFooter

tableView.register(CustomSectionHeader.self, forHeaderFooterViewReuseIdentifier: "customSectionHeader")

4.3 使用 SectionHeader 和 SectionFooter

// 返回 SectionHeader
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "customSectionHeader") as! CustomSectionHeader
    headerView.titleLabel.text = "第 \(section) 组"
    return headerView
}

// 返回 SectionFooter
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "customSectionHeader") as! CustomSectionHeader
    footerView.titleLabel.text = "第 \(section) 组"
    return footerView
}

5. 自定义 SectionHeader 和 SectionFooter 的高度

// 返回 SectionHeader 高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50
}

// 返回 SectionFooter 高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 50
}

6. 自定义 Cell 的高度

// 返回 Cell 高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50
}

7. 自定义 Cell 的编辑样式

// 返回 Cell 编辑样式
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .delete
}

8. 自定义 Cell 的编辑按钮文字

// 返回 Cell 编辑按钮文字
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
    return "删除"
}

9. 自定义 Cell 的移动

// 返回是否允许移动 Cell
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

// 返回移动后的数据源
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    print("将第 \(sourceIndexPath.row) 行移动到第 \(destinationIndexPath.row) 行")
}

10. 自定义 Cell 的删除

// 返回是否允许删除 Cell
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

// 返回删除后的数据源
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    print("删除了第 \(indexPath.row) 行")
}

11. 自定义 Cell 的选中样式

// 返回 Cell 选中样式
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    return true
}

12. 自定义 Cell 的高亮样式

// 返回 Cell 高亮样式
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    print("高亮了第 \(indexPath.row) 行")
}

// 返回 Cell 取消高亮样式
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    print("取消高亮了第 \(indexPath.row) 行")
}

13. 自定义 Cell 的选中样式

// 返回 Cell 选中样式
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    return true
}

// 返回 Cell 选中样式
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    print("选中了第 \(indexPath.row) 行")
}

// 返回 Cell 取消选中样式
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    print("取消选中了第 \(indexPath.row) 行")
}

14. 自定义 Cell 的缩进

// 返回 Cell 缩进
func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
    return 1
}

15. 自定义 Cell 的显示动画

// 返回 Cell 显示动画
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.transform = CGAffineTransform(translationX: 0, y: 50)
    UIView.animate(withDuration: 0.5) {
        cell.transform = CGAffineTransform.identity
    }
}

ImageView 使用

1. 基本使用

1.1 创建 ImageView

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
imageView.image = UIImage(named: "image")
view.addSubview(imageView)

1.2 设置图片

imageView.image = UIImage(named: "image")

1.3 设置图片模式

  • 模式: UIView.ContentMode
    • scaleToFill:缩放填充
    • scaleAspectFit:缩放适应
    • scaleAspectFill:缩放填充
    • redraw:重绘
    • center:居中
    • top:顶部
    • bottom:底部
    • left:左边
    • right:右边
    • topLeft:左上
    • topRight:右上
    • bottomLeft:左下
    • bottomRight:右下
imageView.contentMode = .scaleAspectFit

1.4 设置图片裁剪

imageView.clipsToBounds = true

1.5 设置图片圆角

imageView.layer.cornerRadius = 100

1.6 设置图片边框

imageView.layer.borderWidth = 5
imageView.layer.borderColor = UIColor.red.cgColor

1.7 设置图片阴影

imageView.layer.shadowColor = UIColor.red.cgColor
imageView.layer.shadowOffset = CGSize(width: 10, height: 10)
imageView.layer.shadowOpacity = 0.5
imageView.layer.shadowRadius = 10

1.8 设置图片旋转

imageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 4)

1.9 设置图片缩放

imageView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)

1.10 设置图片平移

imageView.transform = CGAffineTransform(translationX: 50, y: 50)

1.11 设置图片动画

UIView.animate(withDuration: 1) {
    self.imageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 4)
}

ScrollView 使用

1. 基本使用

1.1 创建 ScrollView

let scrollView = UIScrollView(frame: view.bounds)
scrollView.contentSize = CGSize(width: 1000, height: 1000)

view.addSubview(scrollView)

1.2 设置 ScrollView 的代理

scrollView.delegate = self

1.3 设置 ScrollView 的缩放

scrollView.minimumZoomScale = 0.5
scrollView.maximumZoomScale = 2

1.4 设置 ScrollView 的缩放视图

scrollView.zoomScale = 0.5

1.5 设置 ScrollView 滚动方向

scrollView.isDirectionalLockEnabled = true

1.6 设置 ScrollView 的分页

scrollView.isPagingEnabled = true

1.7 设置 ScrollView 的滚动条

scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false

1.8 设置 ScrollView 的滚动条样式

scrollView.indicatorStyle = .black

1.9 设置 ScrollView 的滚动条边距

scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)

1.10 设置 ScrollView 的滚动条偏移

scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)

WebView 使用

1. 基本使用

1.1 创建 WebView

let webView = WKWebView(frame: view.bounds)

view.addSubview(webView)

1.2 加载网页

webView.load(URLRequest(url: URL(string: "https://www.baidu.com")!))

1.3 加载本地网页

webView.load(URLRequest(url: Bundle.main.url(forResource: "index", withExtension: "html")!))

1.4 加载 HTML 字符串

webView.loadHTMLString("<h1>hello world</h1>", baseURL: nil)

1.5 设置 WebView 的代理

webView.navigationDelegate = self

1.6 设置 WebView 的缩放

webView.scrollView.minimumZoomScale = 0.5
webView.scrollView.maximumZoomScale = 2

1.7 设置 WebView 的缩放视图

webView.scrollView.zoomScale = 0.5

1.8 设置 WebView 的滚动条

webView.scrollView.showsHorizontalScrollIndicator = false
webView.scrollView.showsVerticalScrollIndicator = false

1.9 设置 WebView 的滚动条样式

webView.scrollView.indicatorStyle = .black

1.10 设置 WebView 的滚动条边距

webView.scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)

1.11 设置 WebView 的滚动条偏移

webView.scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)

1.12 设置 WebView 的缓存

let config = WKWebViewConfiguration()
config.websiteDataStore = WKWebsiteDataStore.default()
let webView = WKWebView(frame: view.bounds, configuration: config)

1.13 设置 WebView 的缓存策略

let config = WKWebViewConfiguration()
config.websiteDataStore = WKWebsiteDataStore.default()
let webView = WKWebView(frame: view.bounds, configuration: config)
webView.configuration.websiteDataStore.httpCookieStore.setCookie(HTTPCookie(properties: [
    .domain: "www.baidu.com",
    .path: "/",
    .name: "name",
    .value: "value",
    .expires: Date(timeIntervalSinceNow: 3600)
])!)

TextField 使用

1. 基本使用

1.1 创建 TextField

let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
textField.borderStyle = .roundedRect
textField.placeholder = "请输入"
view.addSubview(textField)

1.2 设置 TextField 的代理

textField.delegate = self

1.3 设置 TextField 的键盘类型

// 键盘类型: UIKeyboardType, 默认为 default, 可选的值有: default, asciiCapable, numbersAndPunctuation, URL, numberPad, phonePad, namePhonePad, emailAddress, decimalPad, twitter, webSearch, asciiCapableNumberPad
textField.keyboardType = .numberPad

1.4 设置 TextField 的键盘样式

// 键盘样式: UIKeyboardAppearance, 默认为 default, 可选的值有: default, dark, light
textField.keyboardAppearance = .dark

1.5 设置 TextField 的键盘回车键

// 键盘回车键: UIReturnKeyType, 默认为 default, 可选的值有: default, go, google, join, next, route, search, send, yahoo, done, emergencyCall, continue
textField.returnKeyType = .done

1.6 设置 TextField 的清除按钮

// 清除按钮: UITextFieldViewMode, 默认为 never, 可选的值有: never, whileEditing, unlessEditing, always
textField.clearButtonMode = .whileEditing

1.7 设置 TextField 的左视图

// 左视图: UIView
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
textField.leftViewMode = .always

1.8 设置 TextField 的右视图

// 右视图: UIView
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
textField.rightViewMode = .always

###2. 实现代理方法

// 点击 return 键
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    print("点击了 return 键")
    return true
}

// 点击清除按钮
func textFieldShouldClear(_ textField: UITextField) -> Bool {
    print("点击了清除按钮")
    return true
}

// 点击左视图
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    print("点击了左视图")
    return true
}

// 点击右视图
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    print("点击了右视图")
    return true
}

// 开始编辑
func textFieldDidBeginEditing(_ textField: UITextField) {
    print("开始编辑")
}

// 结束编辑
func textFieldDidEndEditing(_ textField: UITextField) {
    print("结束编辑")
}

// 输入内容
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print("输入内容")
    return true
}

TextView 使用

1. 基本使用

1.1 创建 TextView

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
textView.backgroundColor = .lightGray
textView.text = "hello world"
view.addSubview(textView)

1.2 设置 TextView 的代理

textView.delegate = self

1.3 设置 TextView 的键盘类型

// 键盘类型: UIKeyboardType, 默认为 default, 可选的值有: default, asciiCapable, numbersAndPunctuation, URL, numberPad, phonePad, namePhonePad, emailAddress, decimalPad, twitter, webSearch, asciiCapableNumberPad
textView.keyboardType = .numberPad

1.4 设置 TextView 的键盘样式

// 键盘样式: UIKeyboardAppearance, 默认为 default, 可选的值有: default, dark, light
textView.keyboardAppearance = .dark

1.5 设置 TextView 的键盘回车键

// 键盘回车键: UIReturnKeyType, 默认为 default, 可选的值有: default, go, google, join, next, route, search, send, yahoo, done, emergencyCall, continue
textView.returnKeyType = .done

1.6 设置 TextView 的清除按钮

// 清除按钮: UITextFieldViewMode, 默认为 never, 可选的值有: never, whileEditing, unlessEditing, always

textView.clearButtonMode = .whileEditing

###2. 实现代理方法

// 点击 return 键
func textViewShouldReturn(_ textView: UITextView) -> Bool {
    print("点击了 return 键")
    return true
}

// 点击清除按钮
func textViewShouldClear(_ textView: UITextView) -> Bool {
    print("点击了清除按钮")
    return true
}

Button 使用

1. 基本使用

1.1 创建 Button

let button = UIButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
button.setTitle("按钮", for: .normal)
button.setTitleColor(.black, for: .normal)
button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
view.addSubview(button)

1.2 设置 Button 的标题

button.setTitle("按钮", for: .normal)

1.3 设置 Button 的标题颜色

button.setTitleColor(.black, for: .normal)

1.4 设置 Button 的标题阴影颜色

button.setTitleShadowColor(.red, for: .normal)

1.5 设置 Button 的标题阴影偏移

button.titleLabel?.shadowOffset = CGSize(width: 10, height: 10)

1.6 设置 Button 的标题字体

button.titleLabel?.font = UIFont.systemFont(ofSize: 20)

1.7 设置 Button 的标题偏移

button.titleEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

1.8 设置 Button 的图片

button.setImage(UIImage(named: "image"), for: .normal)

1.9 设置 Button 的图片偏移

button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

1.10 设置 Button 的背景图片

button.setBackgroundImage(UIImage(named: "image"), for: .normal)

1.11 设置 Button 的背景图片偏移

button.backgroundImageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

1.12 设置 Button 的背景颜色

button.backgroundColor = .red

1.13 设置 Button 的圆角

button.layer.cornerRadius = 10

###2. 实现代理方法

// 点击 Button
@objc func buttonClick() {
    print("点击了 Button")
}

Switch 使用

1. 基本使用

1.1 创建 Switch

let `switch` = UISwitch(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
`switch`.addTarget(self, action: #selector(switchClick), for: .valueChanged)
view.addSubview(`switch`)

1.2 设置 Switch 的开关状态

`switch`.isOn = true

1.3 设置 Switch 的开关颜色

`switch`.onTintColor = .red

1.4 设置 Switch 的开关阴影颜色

`switch`.thumbTintColor = .blue

1.5 设置 Switch 的开关阴影图片

`switch`.onImage = UIImage(named: "image")

1.6 设置 Switch 的开关阴影图片

`switch`.offImage = UIImage(named: "image")

###2. 实现代理方法

// 点击 Switch
@objc func switchClick() {
    print("点击了 Switch")
}

Slider 使用

1. 基本使用

1.1 创建 Slider

let slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
slider.minimumValue = 0
slider.maximumValue = 100
slider.value = 50
slider.addTarget(self, action: #selector(sliderClick), for: .valueChanged)
view.addSubview(slider)

1.2 设置 Slider 的最小值

slider.minimumValue = 0

1.3 设置 Slider 的最大值

slider.maximumValue = 100

1.4 设置 Slider 的值

slider.value = 50

1.5 设置 Slider 的最小值颜色

slider.minimumTrackTintColor = .red

1.6 设置 Slider 的最大值颜色

slider.maximumTrackTintColor = .blue

1.7 设置 Slider 的滑块颜色

slider.thumbTintColor = .green

1.8 设置 Slider 的最小值图片

slider.minimumValueImage = UIImage(named: "image")

1.9 设置 Slider 的最大值图片

slider.maximumValueImage = UIImage(named: "image")

###2. 实现代理方法

// 点击 Slider
@objc func sliderClick() {
    print("点击了 Slider")
}

参考资料