在 iOS14 中,蘋果新增了一種卡貼式的彈窗效果。在用戶進行某些操作時,會彈出一個卡片彈窗,提示用戶一些信息。這個效果十分好看且適用于各種場景。下面我們來學(xué)習(xí)一下如何實現(xiàn)這個效果。
在 iOS 中,我們可以使用系統(tǒng)提供的 UIAlertController 來實現(xiàn)卡貼彈窗效果。UIAlertController 是一個 UIViewController 的子類,可以創(chuàng)建不同風(fēng)格的彈窗,包括警告框、操作表、卡片式彈窗等。
下面是一段示例代碼,使用 UIAlertController 實現(xiàn)一個卡片式彈窗:
let alertController = UIAlertController(title: \"這是標(biāo)題\", message: \"這是消息內(nèi)容\", preferredStyle: .alert) let okAction = UIAlertAction(title: \"確定\", style: .default, handler: nil) alertController.addAction(okAction) alertController.addTextField { (textField) in textField.placeholder = \"輸入框\" } let cancelAction = UIAlertAction(title: \"取消\", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil)
上面的代碼會創(chuàng)建一個帶有一個輸入框和兩個按鈕(確定和取消)的卡片式彈窗。我們可以通過給 alertController 添加 UIAlertAction 來設(shè)置按鈕。同時,也可以通過 addTextField 方法來添加輸入框。
除了使用 UIAlertController 之外,我們還可以自定義 UIView 來實現(xiàn)卡貼彈窗效果。這種方法可以更加靈活地定制彈窗的樣式。
下面是一段示例代碼,使用自定義 UIView 實現(xiàn)一個卡片式彈窗:
let alertView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200)) alertView.backgroundColor = .white alertView.layer.cornerRadius = 10 let titleLabel = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: 30)) titleLabel.text = \"這是標(biāo)題\" titleLabel.textAlignment = .center alertView.addSubview(titleLabel) let messageLabel = UILabel(frame: CGRect(x: 0, y: 60, width: 300, height: 50)) messageLabel.text = \"這是消息內(nèi)容\" messageLabel.textAlignment = .center messageLabel.numberOfLines = 0 alertView.addSubview(messageLabel) let okButton = UIButton(type: .system) okButton.frame = CGRect(x: 0, y: 130, width: 150, height: 50) okButton.setTitle(\"確定\", for: .normal) okButton.addTarget(self, action: #selector(okButtonAction), for: .touchUpInside) alertView.addSubview(okButton) let cancelButton = UIButton(type: .system) cancelButton.frame = CGRect(x: 150, y: 130, width: 150, height: 50) cancelButton.setTitle(\"取消\", for: .normal) cancelButton.addTarget(self, action: #selector(cancelButtonAction), for: .touchUpInside) alertView.addSubview(cancelButton) alertView.center = view.center view.addSubview(alertView)
上面的代碼會創(chuàng)建一個帶有標(biāo)題、消息內(nèi)容和兩個按鈕(確定和取消)的卡片式彈窗。我們通過創(chuàng)建 UIView,并向其中添加子視圖來實現(xiàn)自定義彈窗。其中,我們使用 UILabel、UIButton 等組件來構(gòu)造彈窗的內(nèi)容。同時,我們也可以通過設(shè)置 UIView 的背景顏色、圓角等屬性,來定制彈窗的外觀。
iOS14 中新增的卡貼彈窗是一種好看、實用的效果。我們可以使用系統(tǒng)提供的 UIAlertController 或自定義 UIView 來實現(xiàn)這個效果。無論使用哪種方法,我們都可以根據(jù)自己的需求來調(diào)整彈窗的樣式。
希望本文能夠幫助大家實現(xiàn)自己的卡貼彈窗效果!
下一篇:大秦帝師馬化飛第75集(大秦帝師:馬化飛,終老江湖) 下一篇 【方向鍵 ( → )下一篇】
上一篇:永恒興龍集團招聘(永恒興龍集團誠邀有志之士加入) 上一篇 【方向鍵 ( ← )上一篇】
快搜