问题
I am currently adding images to UIAlertAction with the following code (Swift).
purpleAction.setValue(pCircle, forKey: "image")
I want to centre the image in the UIAlertAction if possible. Currently the UIAlertAction has a title that is in the centre, and the image appears on the left hand side.
回答1:
You cannot change the frame of image, you need to build custom alertView for your issue.
回答2:
You can actually hack this with 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"];
I'm not sure if I got the alertViewPadding fudge 100% right to get it perfectly centered, but I think it's doable.
来源:https://stackoverflow.com/questions/34848127/centering-an-image-in-uialertaction-in-uialertcontroller