iOS上每个选项的带有图像的操作表
有没有办法将图像添加到iOS上的操作表中?与苹果应用商店或苹果音乐应用程序上的苹果操作相同。我对苹果文档的基本搜索表明,我不会在操作表中对其进行子类化或添加子视图 “UIActionSheet不是设计成子类的,也不应该向其层次结构中添加视图。”——Apple DocsiOS上每个选项的带有图像的操作表,ios,iphone,swift,Ios,Iphone,Swift,有没有办法将图像添加到iOS上的操作表中?与苹果应用商店或苹果音乐应用程序上的苹果操作相同。我对苹果文档的基本搜索表明,我不会在操作表中对其进行子类化或添加子视图 “UIActionSheet不是设计成子类的,也不应该向其层次结构中添加视图。”——Apple Docs 自iOS 8.3以来,UIActionSheet已被弃用。 使用UIAlertController及其UIAlertActions。 看看UIAlertController与UIActionSheet具有相同的限制,没有真正好的方
自iOS 8.3以来,UIActionSheet已被弃用。 使用
UIAlertController
及其UIAlertAction
s。
看看
UIAlertController
与UIActionSheet
具有相同的限制,没有真正好的方法来定制布局
您可能希望签出这样的库,这些库提供了功能等价物以及更好的自定义选项。要在操作表中添加图像,您需要执行以下操作 Swift
let image = UIImage(named: "myImageName")
let action = UIAlertAction(title: "Action 1", style: .default, handler: nil);
action.setValue(image?.withRenderingMode(.alwaysOriginal), forKey: "image")
目标C
UIAlertAction* action = [UIAlertAction actionWithTitle:@"Action 1" style:UIAlertActionStyleDefault handler:nil];
[action setValue:[[UIImage imageNamed:@"myImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"];
干杯:)用Swift
它仅适用于UIAlertController操作表
Swift 4:如果图像较大且不适合,请使用以下代码和UIImage Extension调整图像大小:
func showAlert() {
let alertController = UIAlertController()
let action = UIAlertAction(title: "Title", style: .default) { (action: UIAlertAction!) in
}
if let icon = icon?.imageWithSize(scaledToSize: CGSize(width: 32, height: 32)) {
action.setValue(icon, forKey: "image")
}
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
并使用此扩展:
extension UIImage {
func imageWithSize(scaledToSize newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
他的解决方案是可行的,但这样做在我看来是不对的。var action=UIAlertAction(标题:“菜单项一”,样式:。默认值,处理程序:nil)action.setValue(图像,forKey:“图像”)我知道并同意,我从来没有发布过这样的破解。这是一个不错的解决方案,但它是一个破解。然后,除了按钮样式相同的自定义控制器之外,没有其他解决方案。这种解决方案的问题是,如果让我们假设苹果将方法的名称从setImage“image”更改为setImg,那么上面的代码将开始崩溃。我知道我们可以使用#选择器进行防护,但仍然不是一个安全的选项。左侧的路线如何?
extension UIImage {
func imageWithSize(scaledToSize newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}