I add Left Navigation Back button in collection view controller with code.
//Add Navigation Bar
navbar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleRightMargin]
navbar.delegate = self
UINavigationBar.appearance().barTintColor = UIColor(red: 0.0/255.0, green:49.0/255.0, blue:79.0/255.0, alpha:0.1)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().isTranslucent = true
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
navItem.title = prefs.value(forKey: "PROVIDER_NAME") as! String?
let image = UIImage(named: "back_image")
navItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(addTapped))
navItem.leftBarButtonItem?.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0)
Back button is so close to the left. I would like to add padding about 10px from the left. So, I changed the code into
navItem.leftBarButtonItem?.imageInsets = UIEdgeInsetsMake(0, 15, 0, 0)
but it is not working and image Back button looks smaller. How can I do to add space to the left of Back button?
I would recommend replacing UINavigationBar with a simple UIView. This way you would gain a full control over the layout of the navigation bar. It wouldn't be anything more than a transparent UIView with a back button and a title label inside. As simple as that.
The real UINavigationBar is more than that. It's meant to manage a stack of UINavigationItem objects. It adjusts itself depends on the current item and knows how to make an animated (and even interactive) transition from one state to another. That's why you can't change much about the bar's appearance. You shouldn't treat it as a regular view.
UPDATE
Another way to achieve this is a little tricky. You can implement it completely from a storyboard and you don't need mess with appearance.
Add UINavigationBar to a view controller.
Add a plain UIView to the left side of UINavigationBar and make its background color completely transparent.
Add UIButton to the view added in the previous step and set a back icon as its image.
Add constraints to the button to align it to the right side of its superview.
Adjust the width of the view so the back button position is exactly where you want it to be.
This is a view hierarchy in the storyboard:
This is how your UINavigationBar will look like (for you the background will be transparent):
Related
I'm starting to learn swiftui and I've run into a problem that is both very basic and easily solvable in UIKit; but after spending days searching the internet and watching WWDC videos I've found no native solution.
The premise is simple: I have an array of songs I want to display in a list; when a user taps on a song view it should highlight the view on press, unhighlight after release, and then play the song (ie trigger an action). Sounds simple right?
Here's what I tried and spent way too much time on:
Using List(selection) + .onEvent(changed): I end up with a UUID (because i've only gotten selection to work with a UUID) that I then have to check against an array of songs to match AND the cell won't unhighlight/select itself; even when I try to manually set the State variable to nil or another generated UUID.
Using .onTap (either on or in the cell): I have to tap on the text of the cell to trigger onTap so I get a lot of taps that just don't work (because I have lots of white space in the cell). I also don't get a nice UI color change on press/release.
So after spending hours trying many different things I've finally come up with a solution and I basically wanted to create an account and share it to hopefully help other developers in my position. Because this so very annoyed me that something so basic took so much effort and time to do.
In the end the best solution I came up with was this:
Using ZStack and an empty button:
edit: I found I need to include and hide the content otherwise the button doesn't grow to fill the space (seems in lists it does for some reason). Though not sure what the hit on performance is of rendering the content twice when hiding it. Maybe a GeometryReader would work better?
struct SelectionView: ViewModifier {
let onSelect: () -> Void
func body(content: Content) -> some View {
ZStack (alignment: .leading) {
Button {
onSelect()
} label: {
content
.hidden()
}
content
}
}
}
extension View {
func onSelection(_ selection: #escaping () -> Void) -> some View {
self.modifier(SelectionView(onSelect: selection))
}
}
then to use it:
SongCell(song: song)
.onSelection {
// Do whatever action you want
}
No messing around with list selection, no weird tap hit boxes, and get the press/release color change. Basically put an empty button in a ZStack and trigger off it's action. Could possibly cause tap/touch issues with more complicated cells (?) but it does exactly what I need it to do for my basic app. I'm just not sure why it took so much effort and why apple doesn't support such a basic use case by default? If I've overlooked something native please do inform me. Thanks.
I got the basic idea what you are trying to do. I'm Going to show simple example. Maybe using this you will be able to find proper solution.
First let's create a color : -
#State var colorToShow : Color = Color.blue
Now in body we have our ZStack or Your cell that we want to deal with : -
ZStack{
colorToShow
}.frame(width: 50, height: 50).padding()
.onLongPressGesture(minimumDuration: 3) {
print("Process Complete")
colorToShow = .green
} onPressingChanged: { pressing in
if pressing {
print("Pressing")
colorToShow = .red
} else {
print("Pressing Released")
colorToShow = .blue
}
}
Here we are using .onLongPressGesture. You can set minimum duration on which you want to perform action. Now on process completion You set what you want to do. OnPressingChange give you a bool value that changes according to user is pressing that button or not. Show color change(Highlight) or do action while bool value is true. When user release button do action or unhighlight since bool value turns false.
Hope you find it useful.
I'm customizing the appearance of the .searchable() modifier of SwiftUI with the appearance API of UISearchBar.
Almost everything works, except the font of the text field, and I have no idea why (setting the font of the cancel button works, or setting the background color or text color of the text field also work, so the correct reference is there).
Talk is cheap, show me the code!
let textAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.systemBlue, // this works
.font: UIFont.boldSystemFont(ofSize: 15) // this doesnt
]
let placeholder = NSAttributedString(
string: "Search...", // this doesnt
attributes: [
.foregroundColor: UIColor.systemGray, // this works
.font: UIFont.boldSystemFont(ofSize: 15) // this doesnt
])
let textFieldAppearance = UITextField
.appearance(whenContainedInInstancesOf: [UISearchBar.self])
textFieldAppearance.backgroundColor = .red // this works
textFieldAppearance.defaultTextAttributes = textAttributes // color works, font not
textFieldAppearance.attributedPlaceholder = placeholder // color works, font or text not
I guess it's time to file a -radar- feedback?
I haven't found a reliable way of customizing this, with the solution posted below there's a glitch on the search bar that happens when SwiftUI re-renders the view (scrolling or just typing on the search bar), that is very obvious on a real device (not so much on the simulator).
Old answer:
Far from ideal, I found a way to make it work, which is introspecting the view searching for the UITextField and setting the font directly. The easiest way to do this is using a library like SwiftUI-Introspect (https://github.com/siteline/SwiftUI-Introspect).
Then on the View you're using .searchable() from just:
.introspectTextField { textField in
textField.font = UIFont.boldSystemFont(ofSize: 15)
}
Fixed! The perfect solution would be to use the appearance API, but I guess we'll have to wait till iOS 16...
Setting the .font and .foregroundColor modifiers after .searchable will do the desired result, but it still doesn't work with .background modifier (if you want it) as the time of this writing (iOS 16).
How do I adjust the padding of a Swift UI "back" navigation button? i.e. the blue "Navigation" text in the image below (Image contributed by someone else on a different question). I want to add more space between the text and the leading edge of the screen.
You can use custom appearance for this purpose configured in the init of view holding NavigationView.
Here is a demo (with big offset for better visibility). Prepared with Xcode 13 / iOS 15.
init() {
let appearance = UINavigationBarAppearance()
appearance.backButtonAppearance.normal.titlePositionAdjustment =
UIOffset(horizontal: 40, vertical: 0)
UINavigationBar.appearance().standardAppearance = appearance
}
i am trying to create a toolbar with buttons. and the button i want to have is an image rather title. The current non working code is:
let imageName = "yourImage.png"
self.myUIBarButtonBack = UIBarButtonItem(image: UIImage(named: imageName), style:.plain, target: self, action: #selector(onClickBarButton))
I have 2 questions:
1. where should i place the yourImage.png in my application
2. is this code sufficient to render image or i need to do things like putting it into imageView component and make it visible etc. ?
The best approach is to add images in xcassets. This is the best way you can organize images. The concept of App slicing applies here.
You don't need to put the image in image view in the case of bar button item.
Try changing the rendring option as Original Image instead of Default.
One way is create custom button and assign to toolbar like navigationbar
self.navigationItem.hidesBackButton = true
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "back_icon"), for: UIControlState.normal)
button.addTarget(self, action:#selector(onClickBackBarItem), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
I need a select box with options and an on select / on change so i can populate a second select box.
My first instinct was to just create one using a surface with a click event and a renderController / scrollview to make my drop down appear. This works wonderfully except that if I leave and come back to the page the zindex of the scrollview breaks and it scrolls over the container size.
Its a bug I need to deal with but my other problem is that with the small Iphone screen size conventional drop downs just eat to much screen real-estate.
This stackoverflow famo.us: how to handle textbox.onchange events had some great hints on how to edit an InputSurface. I thought using that and looking at the code for a Surface I could do it but no luck.
Any Ideas on how to deal with the lack of a select surface?
You can access the value property from inside the callback function:
function SelectSurface(options) {
Surface.apply(this, arguments);
this.onchange = options.onchange;
this._superDeploy = Surface.prototype.deploy;
SelectSurface.prototype.elementType = 'select';
}
SelectSurface.prototype = Object.create(Surface.prototype);
SelectSurface.prototype.constructor = SelectSurface;
SelectSurface.prototype.deploy = function deploy(target) {
target.onchange = this.onchange;
this._superDeploy(target);
};
var regionSelector = new SelectSurface({
size:[140,40],
onchange: regionSelect(),
content: '<option disabled selected style="display:none;">REGION</option><option value="central">CENTRAL</option><option value="northern">NORTHERN</option><option value="pacific">PACIFIC</option><option value="southern">SOUTHERN</option><option value="western">WESTERN</option>',
});
var regionSelect = function(){
return function() {
alert(this.value);
}
};