Cocoa-Touch には control がありUISearchBar
ます。テキストフィールドにある検索アイコン (クリックすると、それぞれのアクションを実行します) が右揃えになるようにカスタマイズする必要があります。通常、左揃えで表示されます。そうすることは可能ですか?研究開発を行ったが見つからなかった...
どうすればいいですか?それを見つけることができる良いチュートリアルはありますか?
Cocoa-Touch には control がありUISearchBar
ます。テキストフィールドにある検索アイコン (クリックすると、それぞれのアクションを実行します) が右揃えになるようにカスタマイズする必要があります。通常、左揃えで表示されます。そうすることは可能ですか?研究開発を行ったが見つからなかった...
どうすればいいですか?それを見つけることができる良いチュートリアルはありますか?
私の要件は、検索アイコンを右側に配置し、X アイコンが表示されるたびに非表示にすることでした。
上記と同様のソリューションを思いつきましたが、少し異なり、Swift 2 と AutoLayout も使用しています。基本的な考え方は、左側のビューを非表示にし、拡大鏡の画像で新しいビューを作成し、自動レイアウトを使用して右側に固定することです。次に、UISearchBarDelegate メソッドを使用して、検索バーのテキストが空でない場合は常に検索アイコンを非表示にします。
class CustomSearchView: UIView {
//the magnifying glass we will put on the right
lazy var magnifyingGlass = UIImageView()
@IBOutlet weak var searchBar: UISearchBar!
func commonInit() {
searchBar.delegate = self
searchBar.becomeFirstResponder()
//find the search bar object inside the subview stack
if let searchField = self.searchBar.subviews.firstObject?.subviews.filter(
{($0 as? UITextField) != nil }).firstObject as? UITextField {
//hides the left magnifying glass icon
searchField.leftViewMode = .Never
//add a magnifying glass image to the right image view. this can be anything, but we are just using the system default
//from the old left view
magnifyingGlass.image = (searchField.leftView! as? UIImageView)?.image
//add the new view to the stack
searchField.addSubview(magnifyingGlass)
//use autolayout constraints to pin the view to the right
let views = ["view": magnifyingGlass]
magnifyingGlass.translatesAutoresizingMaskIntoConstraints = false
searchField.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"H:[view(12)]-|", options: [], metrics: nil, views: views))
searchField.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:[view]-|", options: [], metrics: nil, views: views))
}
}
//hides whenever text is not empty
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
magnifyingGlass.hidden = searchText != ""
}
}