如何左对齐UISearchBar占位符文本

时间:2013-12-04 19:09:55

标签: ios objective-c uiimageview uisearchbar

This is the searchbar that the designers want me to create

我需要像这样制作一个自定义搜索栏。我遇到的问题是左对齐占位符文本,以及将搜索图标放在右侧。我有一个png我尝试在UIImageView中使用的搜索图标,并将UIImageView设置为rightView的{​​{1}} UISearchBar }。这个解决方案没有用,我没有想法。有没有人有解决方案?

10 个答案:

答案 0 :(得分:12)

如果您需要进行这些类型的自定义,请不要使用UISearchBar。您必须使用UITextFieldUIImageView制作自己的,并回复代理电话。

答案 1 :(得分:3)

SWIFT 3

swift 3不允许覆盖占位符属性。这是Drix答案的修改版本。

func setPlaceHolder(placeholder: String)-> String
   {

       var text = placeholder
           if text.characters.last! != " " {

               //                         define a max size

               let maxSize = CGSize(width: UIScreen.main.bounds.size.width - 97, height: 40)

               //                        let maxSize = CGSizeMake(self.bounds.size.width - 92, 40)
               // get the size of the text
               let widthText = text.boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:nil, context:nil).size.width
               // get the size of one space
               let widthSpace = " ".boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:nil, context:nil).size.width
               let spaces = floor((maxSize.width - widthText) / widthSpace)
               // add the spaces
               let newText = text + ((Array(repeating: " ", count: Int(spaces)).joined(separator: "")))
               // apply the new text if nescessary
               if newText != text {
                   return newText
               }

           }

       return placeholder;
   }

并将该函数调用为:

searchBar.placeholder = self.setPlaceHolder(placeholder: "your placeholder text");

答案 2 :(得分:2)

根据Mohittomar的回答,正如@DevC所要求的那样,在占位符的末尾添加空格,这里是swift中的代码:

我在UISearchBar中继承占位符,设置值后,检查最后一个字符是否为空格。然后得到一个空格的大小以及需要添加多少空格以对齐左边。

class SearchBar: UISearchBar, UISearchBarDelegate {
override var placeholder:String? {
    didSet {
        if let text = placeholder {
            if text.last != " " {

// get the font attribute
                let attr = UITextField.s_appearanceWhenContainedIn(SearchBar).defaultTextAttributes
// define a max size
                let maxSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width - 60, 40)
// get the size of the text
                var widthText = text.boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
// get the size of one space
                var widthSpace = " ".boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
                let spaces = floor((maxSize.width - widthText) / widthSpace)
// add the spaces
                let newText = text + (" " * spaces)
// apply the new text if nescessary
                if newText != text {
                    placeholder = newText
                }
            }
        }
    }
}

答案 3 :(得分:2)

Drix的工作解决方案

import Foundation
import UIKit

class LeftAlignedSearchBar: UISearchBar, UISearchBarDelegate {
    override var placeholder:String? {
        didSet {
            if #available(iOS 9.0, *) {
                if let text = placeholder {
                    if text.characters.last! != " " {
                        // get the font attribute
                        let attr = UITextField.appearanceWhenContainedInInstancesOfClasses([LeftAlignedSearchBar.self]).defaultTextAttributes
                        // define a max size
                        let maxSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width - 87, 40)
//                        let maxSize = CGSizeMake(self.bounds.size.width - 92, 40)
                        // get the size of the text
                        let widthText = text.boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
                        // get the size of one space
                        let widthSpace = " ".boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
                        let spaces = floor((maxSize.width - widthText) / widthSpace)
                        // add the spaces
                        let newText = text + ((Array(count: Int(spaces), repeatedValue: " ").joinWithSeparator("")))
                        // apply the new text if nescessary
                        if newText != text {
                            placeholder = newText
                        }
                    }
                }
            }
        }
    }
}

这个方法的外观当iOS 8中没有提供InInstancesOfClasses时,iOS 8有一个解决方法here

答案 4 :(得分:2)

针对Drix的工作swift 3解决方案:

import Foundation
    import UIKit

    class LeftAlignedSearchBar: UISearchBar, UISearchBarDelegate {
        override var placeholder:String? {
            didSet {
                if #available(iOS 9.0, *) {

                    if let text = placeholder {
                        if text.characters.last! != " " {
                            // get the font attribute
                            let attr = UITextField.appearance(whenContainedInInstancesOf: [LeftAlignedSearchBar.self]).defaultTextAttributes
                            // define a max size
                            let maxSize = CGSize(width: UIScreen.main.bounds.size.width - 87, height: 40)
                            // let maxSize = CGSize(width:self.bounds.size.width - 92,height: 40)
                            // get the size of the text
                            let widthText = text.boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:attr, context:nil).size.width
                            // get the size of one space
                            let widthSpace = " ".boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:attr, context:nil).size.width
                            let spaces = floor((maxSize.width - widthText) / widthSpace)
                            // add the spaces
                            let newText = text + ((Array(repeating: " ", count: Int(spaces)).joined(separator: "")))
                            // apply the new text if nescessary
                            if newText != text {
                                placeholder = newText
                            }
                        }
                    }
                }
            }
        }

        /*
        // Only override draw() if you perform custom drawing.
        // An empty implementation adversely affects performance during animation.
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
        */

    }

答案 5 :(得分:0)

如果您希望控件准确地响应您的需求,您应该自己制作自定义控件。 该控件可分为三个部分:

  1. 背景UIImageView
  2. a UITextField
  3. 如果您希望用户与其进行互动,则搜索图标为UIButton
  4. 最简单的方法是创建一个新的类MySearchBar,其中三个部分位于私有界面中:

    @interface MySearchBar ()
    @property (nonatomic, strong) UISearchBar* searchBar;
    @property (nonatomic, strong) UITextField* textField;
    @property (nonatomic, strong) UIButton* button;
    @end
    

    MySearchBar中,您可以创建组件,自定义组件,添加更好的外观和组件。感觉。要获取搜索结果,您的控件可以拥有一个委托id<UISearchBarDelegate>(您的UIViewController),它将基本上模拟标准的UISearchBar。

    剩下的就是在控制器中创建MySearchBar并将代理设置为视图控制器。来自UISearchBarDelegate的邮件可以发送到MySearchBar进行过滤或进行预处理,然后再发送到UIViewController,或直接转到UIViewController

答案 6 :(得分:0)

不需要任何自定义只是这样做......

    searchBar.placeholder=@"Search                                                        ";

搜索栏为其放置器提供了中心文本对齐,所以只需给出一些大文本。如果你的文字很小,那么只需在占位符文字之后使用一些空格。

答案 7 :(得分:0)

Xamarin的版本

SearchBar.MovePlaceHolderLeft();
public static void MovePlaceHolderLeft(this UISearchBar  searchbar)
{
    NSAttributedString text = new NSAttributedString(searchbar.Placeholder ?? "");
    // define a max size
    var maxSize = new CGSize(width: UIScreen.MainScreen.Bounds.Size.Width - 97, height: 40);
    // get the size of the text
    var widthText = text.GetBoundingRect(maxSize, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size.Width;
    // get the size of one space
    var widthSpace = new NSAttributedString(" ").GetBoundingRect(maxSize, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size.Width;
    var spaces = Math.Floor((maxSize.Width - widthText) / widthSpace);
    // add the spaces
    string newText = searchbar.Placeholder;
    for (double i = 0; i < spaces; i++)
    {
        newText += " ";
    }
    searchbar.Placeholder = newText;
}

答案 8 :(得分:0)

这可以从故事板上完成,如果您将其设置为强制从右向左移动,则在搜索栏的属性检查器上有一个名称语义组合框,您具有右对齐搜索栏,并且它具有从左对齐的类似功能

答案 9 :(得分:-2)

现在为时已晚,但如果有人仍然想知道解决方案,那么你可以遵循这个。

UITextField *searchTextField = [searchBarController.searchBar valueForKey:@"_searchField"];

您可以使用上面的代码获取搜索字段。现在只需使用您想要使用的属性,例如。

searchTextField.layer.cornerRadius = 10.0f;
searchTextField.textAlignment = NSTextAlignmentLeft;

PS。文本对齐属性用于文本和占位符。 感谢。