textview中的文本不是垂直居中的

时间:2016-06-12 17:13:22

标签: swift uitextview

我正在尝试创建一个文本视图,其高度遵循其中的行数。我一直致力于约束,但在这里我有一个奇怪的问题:

  • 一开始,所有人都在我想要的中心

enter image description here

  • 当有休息时,文字不再垂直居中并进入左上角

enter image description here

  • 当您删除字符然后返回上一行时,文本仍然是垂直居中的

enter image description here

这是代码

<?php
  $name = $_POST['name'];
  $email = $_POST['email'];
  $msg = $_POST['message'];

  // Array to hold validation errors and response data.
  $errors = array();
  $data = array();

 // Validation
 $nospace_name = trim($_POST['name']);
 $nospace_email = trim($_POST['email']);
 $nospace_message = trim($_POST['message']);

 if (empty($nospace_name))
   $errors['name'] = "Name field is required.";

 if (empty($nospace_email))
   $errors['email'] = "Email field is required.";

 if (empty($nospace_message))
   $errors['message'] = "I would love to see your message.";

 if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
   $errors['bad_email'] = "Please enter a valid email address.";

 if (!empty($errors)) {
   $data['success'] = false;
   $data['errors']  = $errors;
 }
 else {
   $to = "info@example.com";
   $subject = "Website Contact Form: " . $name;

   $headers  = "From: noreply@example.me\r\n";
   $headers .= 'MIME-Version: 1.0' . "\r\n";
   $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
   $headers .= "X-Priority: 1\r\n";
   $headers .= "Reply-To: " . $email;

   // add structure to email
   $message = '<html><body>';
   $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
   $message .= "<tr><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
   $message .= "<tr><td><strong>Message:</strong> </td><td>" . $msg . "</td></tr>";
   $message .= "</table>";
   $message .= "</body></html>";

   $mailSent = mail($to, $subject, $message, $headers);

   if (!$mailSent) {
     $errors['message'] .= "Something went wrong...Please try again later";
     $data['success'] = false;
     $data['errors']  = $errors;
   }
   else {
    $data['success'] = true;
    $data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
  }
 }

 // return all our data to an AJAX call
 echo json_encode($data);
?>

我不明白为什么有这3种不同的情况,你有什么想法解决它吗?

3 个答案:

答案 0 :(得分:3)

您可以尝试在顶部,机器人,左侧和右侧添加插图,即使在第二行出现后也应保持文本居中。

textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5)

答案 1 :(得分:2)

最好保持文本视图本身垂直居中,同时确保文本视图的大小始终适合内容。您可以使用自动布局执行此操作。

将文本视图设置为在其容器中垂直居中,并将高度约束添加到具有低常量值(大约1行文本的高度)的文本视图中。然后将文本视图的内容压缩优先级设置为高于文本视图高度约束的值(请参见屏幕截图)。

enter image description here enter image description here

如果你想看一个有效的例子,我已经在我的这个演示项目的“Main.storyboard”中完成了它: https://github.com/patricklynch/Walkthrough

答案 2 :(得分:0)

也许您可以在输入文字后致电view.layoutIfNeeded()