1
我目前正在为我的应用程序进行更新。我打算添加的新功能之一要求我在UITableViewCell
中替换UILabel
的类。不过,我之前使用Xcode中为单元格提供的默认样式之一,并且禁用了替换类的选项。更改UITableViewCell的默认样式的子视图类
有没有任何解决方法,而不必重写我的大部分代码?
我目前正在为我的应用程序进行更新。我打算添加的新功能之一要求我在UITableViewCell
中替换UILabel
的类。不过,我之前使用Xcode中为单元格提供的默认样式之一,并且禁用了替换类的选项。更改UITableViewCell的默认样式的子视图类
有没有任何解决方法,而不必重写我的大部分代码?
要专门做你在问什么,我只需要改变一些使用一些漂亮的Objective-C黑客的类。这是如何:
1)创建一个新的UILabel子类。在这个例子中,我将使用名为SwizzleLabel
的类。
2)在这个新的标签类中,添加一个方法来对其应用一些样式(比如将文本颜色更改为你想要的样式等)。这基本上是init方法的替代。
-(void)applyStyles {
[self setBackgroundColor:[UIColor blueColor]];
[self setTextColor:[UIColor redColor]];
[self setHighlightedTextColor:[UIColor orangeColor]];
}
3)进口<objc/runtime.h>
无论你将要作出此类变化(例如,在您的视图控制器等)。
4)在您的cellForRowAtIndexPath:
方法中,创建Class
。
Class newLabelClass = objc_getClass("SwizzleLabel");
5)交换类。
object_setClass([cell textLabel], newLabelClass);
6)最后应用一些自定义样式(基本上替换init方法)。现在
[[cell textLabel] performSelector:@selector(applyStyles)];
,你会看到你已经完全换出标签类子类。我的最终cellForRowAtIndexPath:
方法看起来像这样:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] init];
Class newLabelClass = objc_getClass("SwizzleLabel");
object_setClass([cell textLabel], newLabelClass);
[[cell textLabel] performSelector:@selector(applyStyles)];
[[cell textLabel] setText:@"Testing"];
return cell;
}