Creating a fully customized NSAlert

喜夏-厌秋 提交于 2019-12-17 20:21:05

问题


Is it possible to create a fully customized alert? I'm doing it with custom sheets now, but I'd like to have the feature that the sheet is blocking (like -[NSAlert runModal]).

I just want to change the background, really, and the text color, of course.


回答1:


Warning about the recommended solution:

This code causes wasteful and pointless overhead:

for (;;) {
    if ([NSApp runModalSession:session] != NSRunContinuesResponse)
        break;
}

This code is copied straight from the Apple documentation page - but it's meant to show the developer where meaningful code can be inserted for background execution while the modal runs. That is, you should have some code between the break and the closing bracket. But there's no actual code shown in the example - and running it like this simply causes your application to poll the session repeatedly until it ends. It's like the two-year-old in the back seat of the car on a road trip asking, "Are we there yet? Are we there yet? Are we there yet?..."

If you just want straightforward modal execution, where your application presents a modal window and suspends processing of main / background windows until the modal ends, use this:

[NSApp runModalForWindow: self.window];

...and then exit the modal session when the window closes by dropping this into your window controller subclass:

- (void)windowWillClose:(NSNotification *)notification {
    [NSApp stopModal];
}



回答2:


You will need a custom window with custom view drawing, however NSAlert does not allow you to change its window. So you will need to write your own window controller subclass like NSAlert ( though NSAlert is a subclass of NSObject ).




回答3:


I looked around a bit, and found this piece of code :

NSModalSession session = [NSApp beginModalSessionForWindow:sheetWindow];
for (;;) {
    if ([NSApp runModalSession:session] != NSRunContinuesResponse)
        break;
}
[NSApp endModalSession:session];

I call

[NSApp stopModal]

to end the session. Now my code is way cleaner :)



来源:https://stackoverflow.com/questions/8277295/creating-a-fully-customized-nsalert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!