我正在编写一个 iPhone/iPad 应用程序,允许用户填写笔记的空白。每周的笔记都会有所不同。我看到从我们的网络服务器下载 XML 格式的笔记。我正在努力解决的是如何动态构建一个可以对齐文本和输入字段的 View ,类似于下面的示例。
sample image http://www.ccvonline.com/downloads/ios/example.png
我需要让输入控件与文本内联。这可以用 Core Text 来完成吗?有示例代码吗?现在我正在考虑使用 UIWebView 并用 HTML/CSS 构建它。但这感觉有点像作弊。有人有其他想法吗?
最佳答案
从当前行的 NSString 的 sizeWithFont:
方法开始。下载笔记时,确保每个笔记分为两部分,文本字段之前的部分和文本字段之后的部分。
CGSize textSize = [displayStringPart1 sizeWithFont:[UIFont systemFontOfSize:14.0]];
创建该大小的标签并将其添加到 View 层次结构中。
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(22.0, 22.0, textSize.width, textSize.height)];
textLabel.text = displayStringPart1;
// Configure label (shadow, etc.)
[self.view addSubview:textLabel];
[textLabel release];
通过一些简单的算术,您现在知道第一个标签右端的位置。然后您可以添加到文本字段中。您可能需要摆弄框架才能使其正确对齐 - 如果您想要一个好的 UI,请不要忽略此步骤!
// Put text field 5 pixels to the right of the end of the label
// How are you getting the width of the text field? I'm making it 50 here
// Default height for standard text field is 31 pixels
UITextField *answerField = [[UITextField alloc] initWithFrame:CGRectMake((22.0 + textSize.width + 5.0), 18.0, 50.0, 31.0)];
// Configure text field
[self.view addSubview:answerField];
[answerField release];
然后,通过更多的数学运算,您可以创建第二个标签来显示第二部分。该代码与第一段代码类似,不同之处在于要计算 x 位置,您需要执行 22.0 + textSize.width + 5.0 + 50.0 + 5.0
来考虑所有现有的元素。
支持换行会很困难。您可能必须在换行符处手动剪切字符串才能使其适合。上面的代码只处理一行,因为 sizeWithFont:
方法只能返回一个矩形。如果您有多于一行,它永远不会返回小于文本整个宽度的内容,从而使其不太有用。
关于iphone - 创建笔记 View 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7451156/