Я работаю над приложением в течение нескольких месяцев, но, наконец, столкнулся с проблемой, которую я не могу решить самостоятельно, и не могу найти что-либо в Интернете, чтобы помочь.Ошибка визуализации UIAlertView
Я использую несколько обычных UIAlertViews в своем приложении. У некоторых есть 2 кнопки, у некоторых есть 3 кнопки, а у пары есть 2 кнопки и текстовое поле. Однако все имеют ту же проблему. Когда вы вызываете [someAlertView show]; представление предупреждения появляется как обычно, но затем внезапно его графический контекст, кажется, поврежден, как вы можете видеть на скриншоте.
Это происходит на обоих iPhone и IPad тренажеров (как 5.0 и 5.1), так и бывает на устройстве IPAD и iPhone4S, а также.
Изображение, показывающее все, что находится за предупреждением.
Предупреждение по-прежнему работает, я могу щелкнуть по кнопкам, ввести текстовое поле, а затем, когда он отклонит методы делегата, вызывается правильно, и все возвращается к нормальному состоянию. Когда alertView появляется снова, происходит то же самое.
Представление за предупреждением представляет собой подклассу UIScrollView с размером содержимого примерно 4000 пикселей на 1000 с использованием UIImage в качестве фона. Файл png в основном прозрачен, поэтому размер памяти составляет около 80 КБ, а в телефоне нет проблем с его воспроизведением - просмотр прокрутки по-прежнему полностью реагирует и не замедляется. Он также имеет таймер CADisplayLink, прикрепленный к нему как часть подкласса. Я попытался отключить это непосредственно перед отображением alertView, но это не имеет значения, поэтому я сомневаюсь, что это проблема.
Это приложение является частичным переписанием того, что я сделал для университетского проекта, и что он может отображать UIAlertViews поверх вершины scrollView того же размера и подкласса без проблем. Разница между этим приложением и тем, что в моем старом приложении, я подклассифицировал UIAlertView для добавления дополнительных вещей, таких как pickerView, однако я решил, что мне не понравилось, как он выглядел так, что все вышло из предупреждения, и я просто придерживаясь стандартного UIAlertView.
Это как alertView на скриншоте называется:
- (IBAction)loadSimulation:(id)sender {
importAlert = [[UIAlertView alloc] initWithTitle:@"Load Simulation" message:@"Enter Filename:" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Load", nil];
[importAlert setAlertViewStyle:UIAlertViewStylePlainTextInput];
[importAlert showPausingSimulation:self.simulationView]; //Calling [importAlert show]; makes no difference.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[self hideOrganiser]; //Not an issue as the problem occurs on iPad as well.
}
}
При этом, как категоризированного AlertView, чтобы добавить возможность остановить ссылку scrollViews CADisplay.
@interface UIAlertView(pauseDisplayLink)
- (void)showPausingSimulation:(UILogicSimulatorView*)simulationView;
@end
@implementation UIAlertView(pauseDisplayLink)
- (void)showPausingSimulation:(UILogicSimulatorView *)simulationView {
[simulationView stopRunning];
[simulationView removeDisplayLink]; //displayLink needs to be removed from the run loop, otherwise it will keep going in the background and get corrupted.
[self show];
}
У меня нет предупреждений о памяти, когда это происходит, поэтому я сомневаюсь, что это из-за нехватки ресурсов.
Неужели кто-нибудь сталкивался с такой проблемой раньше? Если вам нужна дополнительная информация, я могу попытаться ее предоставить, но я ограничен тем, какой код я могу опубликовать. Любая помощь была бы оценена, я пытался решить это в течение двух недель и не могу понять.
Edit: Оказывается, что это не AlertView на всех (или, вернее, не только alertView), так как эта проблема уходит, когда я извлекаю вид прокрутки позади него, так что должно быть некоторые между ними. Это код для моего UIScrollView подкласса: .h файл: #import #import
@class ECSimulatorController;
@interface UILogicSimulatorView : UIScrollView {
CADisplayLink *displayLink;
NSInteger _updateRate;
ECSimulatorController* _hostName;
}
@property (nonatomic) NSInteger updateRate;
@property (nonatomic, strong) ECSimulatorController* hostName;
- (void) removeDisplayLink;
- (void) reAddDisplayLink;
- (void) displayUpdated:(CADisplayLink*)timer;
- (void) startRunning;
- (void) stopRunning;
- (void) refreshRate:(NSInteger)rate;
- (void) setHost:(id)host;
- (void)setMinimumNumberOfTouches:(NSInteger)touches;
- (void)setMaximumNumberOfTouches:(NSInteger)touches;
@end
.м файл:
#import "UILogicSimulatorView.h"
#import "ECSimulatorController.h"
#import <QuartzCore/QuartzCore.h>
@implementation UILogicSimulatorView
@synthesize updateRate = _updateRate;
@synthesize hostName = _hostName;
- (void)reAddDisplayLink {
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; //allows the display link to be re-added to the run loop after having been removed.
}
- (void)removeDisplayLink {
[displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; //allows the display link to be removed from the Run loop without deleting it. Removing it is essential to prevent corruption between the games and the simulator as both use CADisplay link, and only one can be in the run loop at a given moment.
}
- (void)startRunning {
[self refreshRate:self.updateRate];
[displayLink setPaused:NO];
}
- (void)refreshRate:(NSInteger)rate {
if (rate > 59) {
rate = 59; //prevent the rate from being set too an undefined value.
}
NSInteger frameInterval = 60 - rate; //rate is the number of frames to skip. There are 60FPS, so this converts to frame interval.
[displayLink setFrameInterval:frameInterval];
}
- (void)stopRunning {
[displayLink setPaused:YES];
}
- (void)displayUpdated:(CADisplayLink*)timer {
//call the function that the snakeController host needs to update
[self.hostName updateStates];
}
- (void)setHost:(ECSimulatorController*)host;
{
self.hostName = host; //Host allows the CADisplay link to call a selector in the object which created this one.
}
- (id)initWithFrame:(CGRect)frame
{
//Locates the UIScrollView's gesture recogniser
if(self = [super initWithFrame:frame])
{
[self setMinimumNumberOfTouches:2];
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayUpdated:)]; //CADisplayLink will update the logic gate states.
self.updateRate = 1;
[displayLink setPaused:YES];
}
return self;
}
- (void)setMinimumNumberOfTouches:(NSInteger)touches{
for (UIGestureRecognizer *gestureRecognizer in [self gestureRecognizers])
{
if([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
{
//Changes the minimum number of touches to 'touches'. This allows the UIPanGestureRecogniser in the object which created this one to work with one finger.
[(UIPanGestureRecognizer*)gestureRecognizer setMinimumNumberOfTouches:touches];
}
}
}
- (void)setMaximumNumberOfTouches:(NSInteger)touches{
for (UIGestureRecognizer *gestureRecognizer in [self gestureRecognizers])
{
if([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
{
//Changes the maximum number of touches to 'touches'. This allows the UIPanGestureRecogniser in the object which created this one to work with one finger.
[(UIPanGestureRecognizer*)gestureRecognizer setMaximumNumberOfTouches:touches];
}
}
}
@end
«Хм, неважно, мне не разрешено размещать изображения? Как бесполезно». Это ваш первый пост. Поэтому мы вам не доверяем. Это один из многих преимуществ SO! – dasdom
Я понимаю, почему это просто раздражает, что вокруг так много спамеров, что такие меры необходимы, вот и все, что я получаю. –
Вы пытаетесь показать вид предупреждения из другого потока (например, в фоновом режиме)? Помните: всегда делайте UI-материал ** на главной теме! –