开发者

Replacing a View Property with a New View

I have a View Controller that loads its views from a Xib, and within this Xib, I have a number of subviews that I wan开发者_Go百科t to reuse (e.g. a comment box that gets used in this view and in other views). This is made a tiny bit tricky by the fact that I have properties that refer to this view, which also must be updated. Current solution, which works perfectly fine:

otherView.frame = currentView.frame;
[currentView removeFromSuperview];
[self setCurrentView:otherView];
[self.view addSubview:otherView];

However, I need to do this for many classes, so I thought I'd just create a category on UIViewController to do this view swapping.

- (void)replaceViewProperty:(NSString *)property withNewView:(UIView *)newView {
    SEL propertyMethod = NSSelectorFromString(property);
    UIView *currentView = (UIView *) [self performSelector:propertyMethod];
    newView.frame = currentView.frame;
    [currentView removeFromSuperview];
    [self performSelector:propertyMethod withObject:newView];
    [self.view addSubview:newView];
}

However, the performSelector:withObject: call is incorrect here, because while the name of the getter is e.g. mySubView, the setter would then be setMySubview. Obviously I could manipulate the string to achieve this task, but I'd hope there is a cleaner and more stable way to access the getter and setter for the same ivar. Ideas?


You can use KVC (key-value coding) to set the object manually. In your code it would look something like:

[self setValue:newView forKey:property];

For more infos see the Apple docs on KVC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜