我想出的方法是使用Apple的私有API。您使用這個超級密鑰:"__representer"
在UIAlertAction
對象上致電valueForKey
即可獲得稱爲_UIAlertControllerActionView
的稱謂。
let alertView = UIAlertController(title: "This is Alert!", message: "This is a message!", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertView.addAction(okAction)
self.presentViewController(alertView, animated: true, completion: {
let alertButton = action.valueForKey("__representer")
let view = alertButton as? UIView
view?.accessibilityIdentifier = "okAction_AID"
})
這在完成處理工作要做,因爲這是_UIAlertControllerActionView
將不存在,直到視圖呈現。在我的項目一個側面說明我用以下這些擴展,使事情變得更容易/更易讀:
extension UIAlertController {
func applyAccessibilityIdentifiers()
{
for action in actions
{
let label = action.valueForKey("__representer")
let view = label as? UIView
view?.accessibilityIdentifier = action.getAcAccessibilityIdentifier()
}
}
}
extension UIAlertAction
{
private struct AssociatedKeys {
static var AccessabilityIdentifier = "nsh_AccesabilityIdentifier"
}
func setAccessibilityIdentifier(accessabilityIdentifier: String)
{
objc_setAssociatedObject(self, &AssociatedKeys.AccessabilityIdentifier, accessabilityIdentifier, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
func getAcAccessibilityIdentifier() -> String?
{
return objc_getAssociatedObject(self, &AssociatedKeys.AccessabilityIdentifier) as? String
}
}
所以上面的代碼會被重寫:
let alertView = UIAlertController(title: NSLocalizedString("NMN_LOGINPAGECONTROLLER_ERROR_TITLE", comment: ""), message: message as String, preferredStyle:.Alert)
let okAction = UIAlertAction(title: NSLocalizedString("NMN_OK", comment: ""), style: .Default, handler: nil)
okAction.setAccessibilityIdentifier(InvalidLoginAlertView_AID)
alertView.addAction(okAction)
self.presentViewController(alertView, animated: true, completion: {
alertView.applyAccessibilityIdentifiers()
})
我第一次嘗試涉案試圖瀏覽查看層次結構,但由於UIAlertControllerActionView
不是公共API的一部分,所以變得困難。無論如何,我可能會嘗試如果出於valueForKey("__representer")
爲應用程序商店提交的構建或蘋果可能會給你一個打屁股。
這有效。我剛開了一個蘋果的bug,希望如果我們中的很多人抱怨他們會做點什麼。 – user1366265
任何想法如何設置標題和消息的輔助功能標識符? – user1366265
對不起,我不確定。只需要爲自動化目的設置輔助功能標識符,以便從不需要訪問標題或消息。 –