Ped*_*edi 17 uialertview ios swift
如何使用Swift创建自定义警报?我尝试从Objective c翻译指南但加载全屏布局
为了方便我可以加载透明背景的新布局我试试这个:
listaalertviewcontroller.view.backgroundColor = UIColor.clearColor()
let purple = UIColor.purpleColor() // 1.0 alpha
let semi = purple.colorWithAlphaComponent(0.5)
listaalertviewcontroller.view.backgroundColor = semi
presentingViewController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
self.presentViewController(listaalertviewcontroller, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)
在动画中它是透明的,但是当动画结束时它是不透明的......我在视图中关闭了不透明的选项......我做错了什么?
Sur*_*gch 35
代码在Swift 4和Xcode 9中测试过
我想做类似的事情.首先,UIAlertView有人赞成使用UIAlertController.有关显示警报的标准方法,请参阅此答案:
而且两者UIAlertView并UIAlertController没有真正允许太多的定制.一种选择是使用一些第三方代码.但是,我发现通过显示另一个视图控制器modaly创建自己的警报并不困难.
这里的例子只是一个概念验证.您可以按照自己的方式设计警报.
你应该有两个视图控制器.您的第二个视图控制器将是您的警报.将类名设置为AlertViewContoller,将Storyboard ID设置为alert.(这些都是我们在下面的代码中定义的名称,没有什么特别之处.如果需要,可以先添加代码.如果先添加代码,实际上可能会更容易.)
设置根视图的背景颜色(在警报视图控制器中)以清除.添加另一个UIView并使用约束将其居中.使用它作为你的警报背景,并把你想要的东西放在里面.在我的例子中,我添加了一个UIButton.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "alert")
myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(myAlert, animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
AlertViewController.swift
import UIKit
class AlertViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记连接插座.
而已.你应该能够做出任何你能想象到的警报.不需要第三方代码.
但有时候没有必要重新发明轮子.我对第三方项目SDCAlertView(MIT许可证)印象深刻.它是用Swift编写的,但您也可以将它与Objective-C项目一起使用.它提供广泛的可定制性.
fs_*_*gre 17
这是Swift 3代码.非常感谢@Suragch创建自定义AlertView的绝佳方法.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "storyboardID")
myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(myAlert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
AlertViewController.swift
import UIKit
class AlertViewController: UIViewController {
@IBAction func dismissButtonTapped(sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
为了使它更有趣或在iOS中制作默认效果,您可以添加VisualEffectView或将主UIView的颜色更改为深色并将其alpha设置为70%.我更喜欢第二种方法,因为模糊效果不如具有70 alpha的视图那样平滑.
使用VisualEffectView的效果:
使用70 Alpha的UIView效果:
| 归档时间: |
|
| 查看次数: |
30991 次 |
| 最近记录: |