一个替代 UITextView 的组件,它给您提供了一个:占位符。
技术上与其它解决方案不同,它尝试像 UITextField 的私有 _placeholderLabel
一样工作,因此您不应该会遇到丑陋的bug,比如跳动的文本视图或大量的自定义绘制代码。
您的iOS项目。(已在 iOS 7.x 和 8.0 上测试。也应在 5.x 和 6.x 版本上工作)
注意:这是一个启用 ARC 的代码。您至少需要 Xcode 4.2 和 OS X 10.6。
注意:要运行测试,您需要 Xcode 5 带有 XCTest。
您可以选择克隆这个仓库,并将其项目添加到 Xcode workspace,或者使用 CocoaPods 或 Carthage。
SZTextView *textView = [SZTextView new];
textView.placeholder = @"Enter lorem ipsum here";
textView.placeholderTextColor = [UIColor lightGrayColor];
textView.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18.0];
类似地,您可以使用 attributedPlaceholder
属性来设置一个花哨的 NSAttributedString
作为占位符
NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:@"Enter lorem ipsum here"];
[placeholder addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,2)];
[placeholder addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(2,4)];
[placeholder addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(6,4)];
textView.attributedPlaceholder = placeholder;
这两个属性 placeholder
和 attributedPlaceholder
都是设置为保持同步。如果您设置了 attributedPlaceholder
,之后将 placeholder
设置为其他内容,则设置的文本会被复制到 attributedPlaceholder
,同时尽量保持原始文本属性。
此外,当使用 attributedPlaceholder
设置器时,placeholder
将设置为 attributedPlaceholder.string
。
包含一个简单的演示和一些单元测试。
占位符是可动画化的。只需将 double
属性 fadeTime
配置为您希望动画花费的秒数。
如果您喜欢使用 Interface Builder 来配置您的 UI,则可以使用 UDRA 设置 placeholder
和 placeholderTextColor
的值。
git checkout -b my-new-feature
)git commit -am '添加了一些功能'
)git push origin my-new-feature
)本内容遵循 MIT许可证 发布。
注意
我为了Cocktailicious 开发了这个组件。你可以去看看,*无耻推销*。
请告诉我您是否以及如何使用这个组件。我很好奇。