0

I tried to align the text of an UITextView. My text view is in a cell. Using this link by stackoverflow I tried to align the text. I did it in TableViewCell class like following,

- (void)awakeFromNib {
    [self.postedText addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UITextView *txtview = object;
    CGFloat topoffset = ([txtview bounds].size.height - [txtview contentSize].height * [txtview zoomScale])/2.0;
    topoffset = ( topoffset < 0.0 ? 0.0 : topoffset );
    txtview.contentOffset = (CGPoint){.x = 0, .y = -topoffset};
}

When I'm running this, I got the following error.

observeValueForKeyPath:ofObject:change:context: message was received but not handled. Key path: contentSize Observed object: ; layer = ; contentOffset: {0, 0}; contentSize: {256, 204}> Change: { kind = 1; new = "NSSize: {256, 204}"; } Context: 0x0' *** First throw call stack: (0x1821a02d8 0x1939740e4 0x1821a0218 0x183075d44 0x182fc95c4 0x182fc90e4 0x182fb288c 0x187315944 0x186c8f024 0x186bdd760 0x186525e1c 0x186520884 0x186520728 0x18651febc 0x18651fc3c 0x186c63f90 0x186c63ef4 0x1821582a4 0x182155230 0x182155560 0x1820812d4 0x18b89f6fc 0x186c46fac 0x100060414 0x193ff2a08) libc++abi.dylib: terminating with uncaught exception of type NSException

How may I fix this?

Community
  • 1
  • 1
codebot
  • 2,540
  • 3
  • 38
  • 89
  • please check out [this link](http://stackoverflow.com/questions/6557178/is-it-possible-to-vertically-align-text-inside-labels-with-a-large-frame) – Brian Daneshgar Oct 24 '15 at 17:40

1 Answers1

0

How do you know that self will persist? This is, I take it, a table cell; they come and go. Making the table cell the observer in KVO is very dangerous (as you've just discovered).

In general this approach is not going to be tenable, because the observer needs both to persist beyond the life of the observed and it needs to unregister itself with the observed before the observed goes out of existence. You're not going to be able to do either of those things.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Ok. then is there a way to align the text vertically ? – codebot Oct 24 '15 at 17:46
  • What vertical alignment do you wish to achieve? And what does this even mean? Is this an editable text view? How can we align anything if the user enters a whole lot of text? It is unclear what you wish to achieve (and why). – matt Oct 24 '15 at 18:29