Suj*_*jal 1 alignment ios swift uialertcontroller
我有一个UIAlertController:
let alert = UIAlertController(title: "Add your photo", message: "", preferredStyle: .alert)
var image = UIImage(named: "avatar.png")
image = image?.withAlignmentRectInsets(UIEdgeInsetsMake(0, view.frame.width/2 - (image?.size.width)!/2, 0, 0))
let imageAction = UIAlertAction(title: "", style: .default, handler: nil)
imageAction.setValue(image?.withRenderingMode(.alwaysOriginal), forKey: "image")
alert.addAction(imageAction)
Run Code Online (Sandbox Code Playgroud)
默认情况下,图标左对齐,我尝试使用UIEdgeInset对中心对齐(上面的第3行).考虑到左上角是原点(0,0),我试图将图像定位在水平轴的中心,左边的插入值与代码一样,但图像如下所示.所以我知道这是不正确的.我可以设法通过反复试验把它放在中心.但我想提出一种适当的方法来对齐它.实现这一目标的正确方法是什么?谢谢.
你不应该使用forKey: "image",因为是私人api.
如果要在警报控制器中添加图像,可以尝试使用NSLayoutConstraint,执行此操作:
let alert = UIAlertController(title: "Add your photo", message: "\n\n\n", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Upload", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Add later", style: .default, handler: nil))
let image = UIImageView(image: UIImage(named: "avatar"))
alert.view.addSubview(image)
image.translatesAutoresizingMaskIntoConstraints = false
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: alert.view, attribute: .centerX, multiplier: 1, constant: 0))
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: alert.view, attribute: .centerY, multiplier: 1, constant: 0))
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
self.present(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)
结果是:
| 归档时间: |
|
| 查看次数: |
2554 次 |
| 最近记录: |