Swift changes the navigation bar title to a custom view (picture, button, paragraph selection, and so on)

Source: Internet
Author: User
Tags uikit

The default navigation bar Uinavigationcontroller's caption is text, and the Navigationitem.titleview property makes it easy to replace it with a custom UIView view.

1, using the picture as the title

1
2
let image =  UIImage (named:  "logo" )
self .navigationItem.titleView =  UIImageView (image: image)

2, using the button as the caption

Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let button = UIButton (frame:cgrectmake (0, 0, 110, 110))
Button.setimage (UIImage (named: "Btn3"), Forstate:. Normal)
Button.addtarget (Self,action:selector ("titletapped"), forControlEvents:. Touchupinside)
Self.navigationItem.titleView = button
}

Func titletapped () {
Print ("tapped")
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

3, use the segmented selection control as the caption

Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let items=["Phone", "SMS"] as [Anyobject]
Let Segmented=uisegmentedcontrol (Items:items)
Segmented.center=self.view.center
Segmented.selectedsegmentindex=0///default selected item 1th
Segmented.addtarget (Self, Action: "Segmentdidchange:",
forControlEvents:UIControlEvents.ValueChanged)//Add Value change monitor
Self.navigationItem.titleView = segmented
}

Func Segmentdidchange (Segmented:uisegmentedcontrol) {
Get an index of an option
Print (Segmented.selectedsegmentindex)
Get the selected text
Print (Segmented.titleforsegmentatindex (segmented.selectedsegmentindex))
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.