在 UIAlertController 的 UIAlertAction 中居中图像

Centering an image in UIAlertAction in UIAlertController

我目前正在使用以下代码 (Swift) 将图像添加到 UIAlertAction。 purpleAction.setValue(pCircle, forKey: "image")

如果可能,我想将图像置于 UIAlertAction 的中心。目前 UIAlertAction 的标题位于中间,图像出现在左侧。

您不能更改图像的框架,您需要为您的问题构建自定义 alertView。

您实际上可以使用 imageWithAlignmentRectInsets 破解它:

UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:alertControllerWithTitle:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];
UIImage *topoImage = [UIImage imageNamed:@"foo.png"];
CGFloat alertViewPadding = 22.0;
CGFloat left = -ac.view.frame.size.width/2 + topoImage.size.width + alertViewPadding;
UIImage *centeredTopoImage = [[topoImage imageWithAlignmentRectInsets:UIEdgeInsetsMake(0,left,0,0) ]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[action setValue:centeredTopoImage forKey:@"image"];

我不确定我的 alertViewPadding 软糖是否 100% 正确以使其完美居中,但我认为这是可行的。