你能帮我如何在 SLComposeServiceViewController 中自定义取消和发布按钮吗?
我想更改标题和按钮图像。
SLComposeServiceViewController
自定义 UI 的选项非常有限,目前不包括修改“取消”和“发布”按钮的能力。在当前版本的 iOS 中,避免使用这些按钮的唯一方法是不使用SLComposeServiceViewController
. 共享扩展不需要使用该类,并且可以使用完全自定义的 UI。如果这些按钮不合适,那是您唯一的选择。
我想出了这个解决方案。在最坏的情况下,Apple 会更改并停止使用导航栏,在这种情况下,按钮将简单地恢复为“发布”和“取消”。应该没有崩溃。
对于此示例,我使用“✖”表示取消,使用“✔”表示发布。
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// find the navigation bar
UINavigationBar* bar = self.navigationController.navigationBar;
if (bar == nil)
{
for (UIView* b in self.view.subviews)
{
if ([b isKindOfClass:UINavigationBar.class])
{
bar = (UINavigationBar*)b;
break;
}
}
if (bar == nil)
{
return;
}
}
// find the cancel and post buttons, assuming the post button is on the far right which is a common iOS UI design, to put the positive or confirm action on the right
// also deals with right to left languages (which SLComposeViewController does not support yet), where the post button will be on the left
UIButton* postButton = nil;
UIButton* cancelButton = nil;
BOOL rightToLeft = NO;
if ([UIView.class respondsToSelector:@selector(userInterfaceLayoutDirectionForSemanticContentAttribute:)])
{
rightToLeft = ([UIView userInterfaceLayoutDirectionForSemanticContentAttribute:bar.semanticContentAttribute] == UIUserInterfaceLayoutDirectionRightToLeft);
}
CGFloat x = (rightToLeft ? FLT_MAX : FLT_MIN);
for (UIView* v in bar.subviews)
{
if ([v isKindOfClass:UIButton.class] && ((rightToLeft && v.frame.origin.x < x) || (!rightToLeft && v.frame.origin.x > x)))
{
x = v.frame.origin.x;
if (postButton != nil)
{
cancelButton = postButton;
}
postButton = (UIButton*)v;
}
}
// if we found a cancel UIButton, set the title
if (cancelButton != nil)
{
[cancelButton setTitle:@"✖" forState:UIControlStateNormal];
}
// if we found a post UIButton, set the title
if (postButton != nil)
{
[postButton setTitle:@"✔" forState:UIControlStateNormal];
}
}
我刚刚找到了一种方法:
class CustomServiceViewController: SLComposeServiceViewController {
override func viewDidLoad() {
let navigationBar = view.subviews.first?.subviews?.last? as? UINavigationBar
let postButton = navigationBar?.subviews.last? as? UIButton
let cancelButton = navigationBar?.subviews.last? as? UIButton
postButton?.setTitle("Done", forState: .Normal)
}
}
请注意 - 这是一个脆弱的解决方案,基于未记录的内部结构SLComposeServiceViewController